結論
感覺數學含義上明白了,但是關于數據的類型的理解還需要再加深(比剛才懵懂的感覺好多了)。
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?