StackedCrooked
StackedCrooked

Reputation: 35485

Function composition in Clojure?

Can Clojure implement (g ∘ f) constructions like Haskell's g . f? I'm currently using workarounds like (fn [n] (not (zero? n))), which isn't nearly as nice :)

Upvotes: 35

Views: 9692

Answers (3)

Brian Carper
Brian Carper

Reputation: 72926

You can use Clojure's reader-macro shortcut for anonymous functions to rewrite your version in fewer keystrokes.

user=> (#(not (zero? %)) 1)
true

For the specific case of composing not and another function, you can use complement.

user=> ((complement zero?) 1)
true

Using not in combination with when and if is common enough that if-not and when-not are core functions.

user=> (if-not (zero? 1) :nonzero :zero)
:nonzero

Upvotes: 13

Michiel Borkent
Michiel Borkent

Reputation: 34800

Another way is (reduce #(%2 %1) n [zero? not]) but I like (comp not zero?), already mentioned by Michal, better.

Upvotes: 4

Michał Marczyk
Michał Marczyk

Reputation: 84331

There is a function to do this in clojure.core called comp. E.g.

((comp not zero?) 5)
; => true

You might also want to consider using -> / ->>, e.g.

(-> 5 zero? not)
; => true

Upvotes: 55

Related Questions