core.mal: add and test right fold
authorNicolas Boulenguez <nicolas.boulenguez@free.fr>
Sat, 11 May 2019 10:39:02 +0000 (12:39 +0200)
committerNicolas Boulenguez <nicolas.boulenguez@free.fr>
Fri, 17 May 2019 23:52:12 +0000 (01:52 +0200)
core.mal
tests/step8_macros.mal

index 2448017..efd2ade 100644 (file)
--- a/core.mal
+++ b/core.mal
       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))
 
index aac3f08..c1e6782 100644 (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