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 :)
views:
263answers:
3
+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
2010-05-12 19:41:30
A:
Another way is (reduce #(%2 %1) n [zero? not])
but I like (comp not zero?)
, already mentioned by Michal, better.
Michiel Borkent
2010-05-12 19:52:05
+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
2010-05-12 20:34:48
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
2010-05-12 23:25:42