ashishwave wrote:
> ruby integrates power of functional programming from lisp , purest OO
> from smalltalk, prototype oriented power from self etc etc into one
> single language
> 
> i just was wondering that whether the heavy developers/users of
> reactive languages like kanaputs or reactive-C etc will ever get
> reactive features in ruby.
> 
> in kanaputs, If the variable 'c' is defined as  c = a + b; and if the
> reactivity of 'c' is set (c.reactive = true;), then each time the
> value of 'a' or 'b' changes then the value of 'c' is updated as the
> result of the addition
> 
> 
> bye :-)
> Ashish
> ashishwave / yahoo.com.
> 

I think this may give you some ideas. A Reactive object
has a number of reactive objects it depends on as well
as a block to calculate it's own value. The self value
is calculated lazily and cached. It is only recalculated
when an object it depends on set's it's dirty flag
by calling notify.


class Reactive

    # On change of value dependants are notified
    # of updates
    def value=(val)
       @value=val
       @depends.each do |d|
          d.notify
       end
    end

    # Add d as a listener
    def notify_me d
       @depends << d
    end

    # Get the cached value unless the
    # dirty flag has been set then
    # recalc the value from the block
    def value
       if @block && @dirty
          argv = []
          @args.each do |a|
             if a.respond_to? :value
                argv << a.value
             else
                argv << a
             end
          end
          @value = @block.call *argv
       end
       @dirty=false
       @value
    end

    # Notify this object that at
    # least one dependant has changed.
    def notify
       @dirty=true
    end

    # Init the class with the dependant
    # reative variables and a block to
    # evaluate to compute the value
    # of this object.
    def initialize *args, &block
       @depends = []
       if block_given?
          @args = args
          @block = block
          @args.each do |a|
             a.notify_me self
          end
       else
          # This is a literal
          @value = *args
       end
       @dirty=true
    end

end


a = Reactive.new(10)
b = Reactive.new(20)
c = Reactive.new a,b do |_a,_b|
    _a + _b
end
d = Reactive.new b,c do |_b,_c|
    _b + _c
end


vars = {:a=>a,:b=>b,:c=>c,:d=>d}

vars.each do |k,v|
    puts "#{k} #{v.value}"
end

puts "------------------"

a.value = 40
vars.each do |k,v|
    puts "#{k} #{v.value}"
end

------------------

Output is

:!ruby reactive.rb
c 30
d 50
a 10
b 20
------------------
c 60
d 50
a 40
b 20




--
Brad Phelan
http://xtargets.com