Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created September 16, 2015 12:03
Fold Zip in clojure with clojure.test
(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)))
(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)
@MikeMKH
Copy link
Author

MikeMKH commented Sep 16, 2015

@MikeMKH
Copy link
Author

MikeMKH commented Oct 5, 2015

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