Skip to content

Instantly share code, notes, and snippets.

@taxigy
Created March 7, 2018 00:03
Show Gist options
  • Save taxigy/adc857a196035e940a246ec74966c456 to your computer and use it in GitHub Desktop.
Save taxigy/adc857a196035e940a246ec74966c456 to your computer and use it in GitHub Desktop.
Haskell vs Clojure: function composition — Learn You a Haskell for Great Good!
;; without composition
(repeat 2 (apply * (map #(* 3 %) (map max [1 2] [4 5]))))
;; with composition
((comp (partial repeat 2)
(partial apply *)
(partial map (partial * 3)))
(map max [1 2] [4 5]))
;; with thread macro
(->> (map max [1 2] [4 5])
(map (partial * 3))
(apply *)
(repeat 2))
-- without composition
replicate 2 (product (map (* 3) (zipWith max [1, 2] [4, 5])))
-- with composition
replicate 2 . product . map (* 3) $ zipWith max [1, 2] [4, 5]
@bpiel
Copy link

bpiel commented Mar 7, 2018

The trade-off being that haskell doesn't support multi-arity functions.

Of course, with clojure's macros, you can create new syntax. Something as simple as this:

(defmacro dot-comp
  [& body]
  (->> body
       (partition-by #{'.})
       (remove #{'(.)})
       (apply list '->>)))

let's you write:

(dot-comp map max [1 2] [4 5] . map (partial * 3) . apply * . repeat 2)

I also like that in the clojure example, the operations get applied in left->right order, as opposed to the haskell example's right->left ordering.

Learn you clojure for great good?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment