Skip to content

Instantly share code, notes, and snippets.

@HerbM
Created September 3, 2016 05:08
Show Gist options
  • Save HerbM/e2cb1ca4d2b8d01d89b07fea8431f86b to your computer and use it in GitHub Desktop.
Save HerbM/e2cb1ca4d2b8d01d89b07fea8431f86b to your computer and use it in GitHub Desktop.
Re-implement Clojure "comp" for 4Clojure problem #58
(ns clojure4.core)
;;; Re-implement Clojure "comp" for 4Clojure problem #58 (as "komp")
(defn komp
([] (fn [n] (identity n)))
([fn1] (fn [& n] (apply fn1 n)) )
([fn1 fn2] (fn [& n]
(fn1 ((fn [m] (apply fn2 m)) n))))
([fn1 fn2 & fns] (fn [& n]
(fn1 ((fn [m] (apply (apply komp (conj fns fn2)) m )) n )))))
;;; tests
((komp inc inc) 0)
((komp dec + inc ) 0)
((komp inc inc inc inc inc ) 0)
(= true ((komp zero? #(mod % 8) +) 3 5 7 9))
(= "HELLO" ((komp #(.toUpperCase %) #(apply str %) take) 5 "hello world"))
((komp inc (partial * 2) ) 7)
((komp rest reverse) [1 2 3 4])
;;; Examples from Closuredocs.org comp page
(def negative-quotient (komp - /))
;; #'user/negative-quotient
(negative-quotient 8 3) ;;=> -8/3
(def concat-and-reverse (komp (partial apply str) reverse str))
;; #'user/concat-and-reverse
(concat-and-reverse "hello" "clojuredocs")
;;=> "scoderujolcolleh"
((komp str +) 8 8 8) ;;=> "24"
(map
(komp - (partial + 3) (partial * 2))
[1 2 3 4])
;;=> (-5 -7 -9 -11)
(filter (komp not zero?) [0 1 0 2 0 3 0 4])
;;=> (1 2 3 4)
(def countif (komp count filter))
#'user/countif
(countif even? [2 3 1 5 4])
;;=> 2
( (komp second reverse) '("a" 2 7 "b"))
;;=> 7
( #((apply komp first (repeat %2 rest)) %1) [1 2 3 4 5 6] 3 )
;;=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment