Created
September 16, 2015 12:03
Fold Zip in clojure with clojure.test
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
(ns fold-zip) | |
(defn fold-zip | |
"zip f = fold (λx xs ys → f x y : xs ys) [ ]" | |
[f & colls] | |
(reduce #(conj %1 (apply f %2)) [] (apply map vector colls))) |
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
(ns fold-zip.tests | |
(require | |
[clojure.test :refer [deftest testing is are run-tests]] | |
[fold-zip :as sut])) | |
(deftest fold-zip-tests | |
(testing "Given empty collections with identity it must return an empty collection" | |
(is (empty? (sut/fold-zip identity [] [])))) | |
(testing "Given collections with vector it must return collection zip together" | |
(are [xs ys] (= (map vector xs ys) (sut/fold-zip vector xs ys)) | |
[1] [1] | |
[1 2 3] [1 2 3] | |
[1] [1 2] | |
[1 2] [1])) | |
(testing "Given numerical collections with math operations it must return same as map" | |
(are [f] | |
(are [xs ys] (= (map f xs ys) (sut/fold-zip f xs ys)) | |
[1] [1] | |
[1 2 3] [1 2 3] | |
[1] [1 2] | |
[1 2] [1] | |
[42.5 41.5] [11.1 16.5]) | |
+ | |
/ | |
* | |
-)) | |
(testing "Given collections with collection operations it must return same as map" | |
(are [f] | |
(are [coll] (= (map f coll coll coll coll) (sut/fold-zip f coll coll coll coll)) | |
["Mike" "Harris" "clojure" "programmer"] | |
[1 2 3 4 5] | |
[true false true false false]) | |
list | |
vector))) | |
(run-tests) |
See also my blog posted which goes with this gist http://comp-phil.blogspot.com/2015/10/fold-zip-up.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on map in http://www.cs.nott.ac.uk/~gmh/fold.pdf