Skip to content

Instantly share code, notes, and snippets.

@purukaushik
Last active February 11, 2017 07:54
Show Gist options
  • Save purukaushik/5ab622eb4e4f03d872173f3d48ea7c03 to your computer and use it in GitHub Desktop.
Save purukaushik/5ab622eb4e4f03d872173f3d48ea7c03 to your computer and use it in GitHub Desktop.
Basic Functional building blocks- map, filter, reduce, etc ab initio in clojure
(defn map
"(map f coll) takes a function f and applies it to each element in coll and returns a collection"
([f coll] (map f coll []))
([f coll acc]
(if (empty? coll)
acc
(map f (rest coll) (cons (f (first coll)) acc)))))
(defn filter
"(filter f coll) takes a function f that computes a predicate condition on each element in coll and filtered collection is returned"
([f coll] (filter f coll []))
([f coll acc]
(if (empty? coll)
acc
(if (f (first coll))
(filter f (rest coll) (cons (first coll) acc))
(filter f (rest coll) acc)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment