rubyonrails:Ruby中实现stream

  流是通过延时求值实现Ruby中实现stream也是可以做到可惜就是没有尾递归优化按照sicp首要是两个:delay和force:

def mem_proc(exp)
 alread_run=false
 result=false
 lambda{
   !alread_run
   result=exp.call
   alread_run=true
   result
  
   result
  end
 }
end
def force(delayed_object)
 delayed_object.call
end
def delay(exp)
 mem_proc(lambda{exp})
end
  

  delay返回延时对象就是对于未来某个时间求值表达式承诺;force以延时对象为参数进行相应求值工作这里mem_proc用于记忆已经求值过表达式定义streamconstructor和selector:

def cons_stream(a,b)
  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 


  用Ruby中充当“粘合剂”stream_car直接返回第个元素而stream_cdr需要用force求值表达式履行承诺另外将空作为the-empty-stream再定义几个高阶map和foreach其他如filter和此类似:

def stream_enumerate_erval(low,high)
  low>high
  
 
  cons_stream(low,stream_enumerate_erval(low.succ,high))  
 end
end
def stream_ref(s,n)
  n0
  stream_car(s)
 
  stream_ref(stream_cdr(s),(n-1))  
 end
end
def stream_map(proc,s)
  stream_null?(s)
  
 
  cons_stream(proc.call(stream_car(s)),stream_map(proc,(stream_cdr(s))))  
 end
end
def stream_for_each(proc,s)
  stream_null?(s)
  :done
 
  proc.call(stream_car(s))
  stream_for_each(proc,stream_cdr(s))  
 end
end
def display_stream(s)
 stream_for_each(lambda{|item| puts item},s)
end
def stream_filter(pred,s)
  stream_null?(s)
  
 els pred.call(stream_car(s))
  cons_stream(stream_car(s),stream_filter(pred,stream_cdr(s)))
 
  stream_filter(pred,stream_cdr(s)) 
 end
end
  最后看下例子:

puts "s:"
s=stream_enumerate_erval(1,5)
display_stream(s)
puts "odd_s:"
odd_s=stream_filter(lambda{|x| x%21},s)
display_stream(odd_s)
puts "ss:"
ss=stream_map(lambda{|x|x*x},s)
display_stream(ss)


Tags:  programmingruby ruby教程 rubyday rubyonrails

延伸阅读

最新评论

发表评论