Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function composition in Clojure?

Tags:

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

like image 717
StackedCrooked Avatar asked May 12 '10 19:05

StackedCrooked


2 Answers

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 
like image 102
Michał Marczyk Avatar answered Nov 09 '22 11:11

Michał Marczyk


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 
like image 35
Brian Carper Avatar answered Nov 09 '22 12:11

Brian Carper