1
1
mirror of https://github.com/kanaka/mal.git synced 2024-09-11 13:55:55 +03:00

core.mal: add and test right fold

This commit is contained in:
Nicolas Boulenguez 2019-05-11 12:39:02 +02:00
parent e044a11ab1
commit 840faeb26d
2 changed files with 27 additions and 0 deletions

View File

@ -24,6 +24,17 @@
init
(reduce f (f init (first xs)) (rest xs)))))
;; Right fold (f x1 (f x2 (.. (f xn init)) ..))
(def! foldr
(fn* [f init xs]
;; f : Element Accumulator -> Accumulator
;; init : Accumulator
;; xs : sequence of Elements x1 x2 .. xn
;; return : Accumulator
(if (empty? xs)
init
(f (first xs) (foldr f init (rest xs))))))
;; Returns the unchanged argument.
(def! identity (fn* (x) x))

View File

@ -167,6 +167,22 @@ x
(reduce str "a" ["b" "c"])
;=>"abc"
;; Testing foldr
(foldr + 7 [])
;=>7
(foldr + 7 [1])
;=>8
(foldr + 7 [1 2])
;=>10
(reduce * 7 [-1 2])
;=>-14
(foldr concat [1] [[2] [3]])
;=>(2 3 1)
(foldr str "a" ["b" "c"])
;=>"bca"
(foldr cons [4 5] [2 3])
;=>(2 3 4 5)
;; Testing every?
(every? first [])
;=>true