Hacker News new | ask | show | jobs
by adityaathalye 250 days ago
If the language allows passing lists of functions, then `comp` can be implemented by hand: https://clojuredocs.org/clojure.core/comp

And re-implementing `comp` by hand can teach us more than we bargained for (all the way to compiler technology)... I blogged about it here: https://www.evalapply.org/posts/lessons-from-reimplementing-...

  ;; Clojure source code for `comp` (since Clojure v1.0)
  (defn comp
    "Takes a set of functions and returns a fn that is the composition
    of those fns.  The returned fn takes a variable number of args,
    applies the rightmost of fns to the args, the next
    fn (right-to-left) to the result, etc."
    {:added "1.0"
     :static true}
    ([] identity)
    ([f] f)
    ([f g] 
       (fn 
         ([] (f (g)))
         ([x] (f (g x)))
         ([x y] (f (g x y)))
         ([x y z] (f (g x y z)))
         ([x y z & args] (f (apply g x y z args)))))
    ([f g & fs]
       (reduce1 comp (list* f g fs))))
2 comments

Oh and, the arrow-kt library bolts this onto kotlin.

Utilities for functions: https://arrow-kt.io/learn/collections-functions/utils/