Implementing Stream in Ruby

Source: Internet
Author: User
Tags expression

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.