结论
感觉数学含义上明白了,但是关于数据的类型的理解还需要再加深(比刚才懵懂的感觉好多了)。
a = [1, 2, 3 ,4]
c = a.map{|x| (lambda {|y| y > x})} #其中map是形成size(a)个instance of Proc class
c[2].call 3 #这个大概的意思是说,令x = a[2], y=3, 然后运算y > x
c.count{|x| x.call 5} #这个比较明确
first-class expression具有哪些特性呢?
- 它可以作为函数(或者方法)的返回值。
- 它可以存储在对象中,并且可以像普通的对象(如numbers、string)进行传参,也可以放置在任何表达式可以放置的地方。
What is Procs?
procs简单的说,是blocks的加强版(它具有对象的属性)。其中blocks是通过yield方法来调用的。但对于blocks而言,它无法返回,无法存储在对象中,也无法将其放置在array等容器中。So blocks are second(not first)。But Instances of Proc class are first class.
How to use Procs?
有很多的方法来产生Proc对象,但我们这节课只会讲一个,即通过lambda + blocks的方法。
code examples
a = [3, 5, 7, 9]
b = a.map{|x| x + 1}
i = a.count{|x| x > 3}
如果我们要创建an array of closures(I want an array where the ith position is a little function.)
a = [3, 5, 7, 9]
c = a.map{|x| (lambda {|y| y>=x})}
c[2].call(4)
c.count{|x| x.call(5)}
Moral
- First-class makes closures more powerful than blocks.
- But blocks are more convenient and cover most uses.
- This help us understand what first-class means
- Language design question:When is convenience worth making something less general and powerful?