-
-
Save stoeckley/93e590ec9d99338af5daebaa29fac51b to your computer and use it in GitHub Desktop.
fold-right and reduce-right in Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(use 'clojure.test) | |
(defn fold-right [f z coll] | |
(loop [[c & cs] coll rvsd '()] | |
(if (nil? c) | |
(loop [acc z [r & rs] rvsd] | |
(if r (recur (f r acc) rs) acc)) | |
(recur cs (cons c rvsd))))) | |
(defn reduce-right [f coll] | |
(loop [[c & cs] coll rvsd '()] | |
(if (nil? cs) | |
(loop [acc c [r & rs] rvsd] | |
(if r (recur (f r acc) rs) acc)) | |
(recur cs (cons c rvsd))))) | |
(deftest test-fold-right | |
(are [result expected] (= result expected) | |
(fold-right - 2 '(3 1 4 1 5 9)) ; (- 3 (- 1 (- 4 (- 1 (- 5 (- 9 2)))))) | |
3 | |
(fold-right #(cons (* 2 %) %2) '() '(3 1 4 1 5 9 2)) ; map #(* 2 %) | |
'(6 2 8 2 10 18 4) | |
(fold-right #(concat %2 (list %)) '() '(3 1 4 1 5 9 2)) ; reverse | |
'(2 9 5 1 4 1 3) | |
)) | |
(deftest test-reduce-right | |
(are [result expected] (= result expected) | |
(reduce-right - '(3 1 4 1 5 9 2)) | |
3 | |
(reduce-right #(cons (* 2 %) (if (seq? %2) %2 (list (* 2 %2)))) '(3 1 4 1 5 9 2)) | |
'(6 2 8 2 10 18 4) | |
(reduce-right #(concat (if (seq? %2) %2 (list %2)) (list %)) '(3 1 4 1 5 9 2)) | |
'(2 9 5 1 4 1 3) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment