Clojure has several options for composing functions. There are composition functions for:
- Apply: for expand arguments
- Partial: for arguments not yet set
- Comp: for consistent connection results through several functions
- Juxt: to apply one argument to multiple functions
However, AFAIK does not exist such composite functions that include branching. Are there any functions that make up functions in branches, like a functional version of if or cond ?
Of course, if the version is easy to make (although this implementation may not be the fastest):
(defn iff ([pred rtrue] (iff pred rtrue identity)) ([pred rtrue rfalse] (fn [& args] (if (apply pred args) (apply rtrue args) (apply rfalse args)))))
In this case, the question of returning by default in case of "else" by the rule, or if in this case it is necessary to return nil, can be discussed.
Using such a function can lead to easier code reading. Instead of #(if (string? %) (trim %) %) it will become (iff string? trim) or with cond version:
(condf string? trim, vector? (partial apply str), :else identity)
Do other FP languages โโhave such constructs? I can imagine that this can be convenient in compositions with comp and juxt. Why not Clojure?
Bonus points for realistic implementations iff / condf :)
source share