Ruby language in the programming world can be said to be an up-and-comer, the purpose is to help programmers more simple and flexible to write code programs to complete their own functional needs. For example, in Ruby implementation stream.
According to SICP, the first is two functions: delay and Force:
def mem_proc(exp)
alread_run=false
result=false
lambda{
if !alread_run
result=exp.call
alread_run=true
result
else
result
end
}
end
def force(delayed_object)
delayed_object.call
end
def delay(exp)
mem_proc(lambda{exp})
end
The delay function returns the delay object, which is the promise to evaluate the expression for some time in the future; The Force function takes the delay object as the parameter, carries on the corresponding evaluation work, here the Mem_proc is used for the memory already evaluated expression. Ruby implements the constructor and selector functions of the stream:
def cons_stream(a,b)
return a,delay(b)
end
def stream_car(s)
s[0]
end
def stream_cdr(s)
force(s[1])
end
def stream_null?(s)
s.nil? or s==[]
end