tags:

views:

263

answers:

3

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 :)

+8  A: 

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
Michał Marczyk
A: 

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

Michiel Borkent
+2  A: 

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
Brian Carper
The reader-macro shortcut seems very useful as the code is succinct and readable. I also didn't know about "if-not" and "when-not", thanks!
StackedCrooked