我們可以看到,我們可以使用reduce
/foldl1
作爲函數by which we can define other higher order functions such as map, filter and reverse。爲什麼fold和reduce被認爲是根本性的 - 當然,所有的東西都是根據cons和car定義的?
(defn mapl [f coll]
(reduce (fn [r x] (conj r (f x)))
[] coll))
(defn filterl [pred coll]
(reduce (fn [r x] (if (pred x) (conj r x) r))
[] coll))
(defn mapcatl [f coll]
(reduce (fn [r x] (reduce conj r (f x)))
[] coll))
我們也似乎能夠按照foldr
的方式做到這一點。根據foldr
from Rich Hickey's Transducers talk在17:25,這裏是map
和filter
。
(defn mapr [f coll]
(foldr (fn [x r] (cons (f x) r))
() coll))
(defn filterr [pred coll]
(foldr (fn [x r] (if (pred x) (cons x r) r))
() coll))
現在,我們可以定義map
,foldl
(reduce
)和foldr
在first
,rest
和cons
(car
,cdr
和cons
)方面:
(defn foldr [f z xs]
(if (null? xs)
z
(f (first xs) (foldr f z (rest xs)))))
(defn foldl [f z xs]
(if (null? xs)
z
(foldl f (f z (first xs)) (rest xs))))
(defn map [f lst]
(if (null? lst)
'()
(cons (f (first lst)) (map f (rest lst)))))
我的問題是爲什麼fold
和reduce
被認爲是根本性的 - 當然一切都按照cons
,cdr
和car
?這是不是在看錯級別的東西?
([與香蕉,鏡頭 信封和鐵絲網函數式編程] http://wwwhome.ewi.utwente.nl/~fokkinga/mmf91m.pdf )似乎相關。我也懷疑是否有不止一種「基本」的觀察方式 - Clojure的實現方式的確如此,但是也有一種描述事物的數學方法。 – 2014-09-29 12:06:15
我真的很感激這個評論馬特 - 我只是想知道是否有一些我們可以分類的「積木開始的地方」。有人說Lisp是麥克斯韋軟件方程http://www.michaelnielsen.org/ddi/lisp-as-the-maxwells-equations-of-software/ - 但這個問答的主題是,這僅限於'lists',有時候你想用'fold'來轉換非列表結構。 – hawkeye 2014-09-29 22:20:01
請注意,'cons','car'和'cdr'在客觀意義上不是原始的:您可以用'lambda'來定義它們。那麼爲什麼要求把這一切都歸結爲這三種特定的原始操作,而不是其他的操作呢?這都是相對的。 – amalloy 2014-09-29 23:56:25