Elisp Function Composition

During my recent Elisp hacking I've run into the situation enough times where I really wanted function composition that I officially implemented it for myself. While there is an apply-partially function, Elisp does not currently come with a compose function. Here's an Elisp definition,

;; ID: f0c736a9-afec-3e3f-455c-40997023e130
(defun compose (&rest funs)
  "Return function composed of FUNS."
  (lexical-let ((lex-funs funs))
    (lambda (&rest args)
      (reduce 'funcall (butlast lex-funs)
              :from-end t
              :initial-value (apply (car (last lex-funs)) args)))))

Here it is in action with three functions.

(funcall (compose 'prin1-to-string 'random* 'exp) 10)

I'll be using this in later posts (and linking back here when I do).

Have a comment on this article? Start a discussion in my public inbox by sending an email to ~skeeto/public-inbox@lists.sr.ht [mailing list etiquette] , or see existing discussions.

This post has archived comments.

null program

Chris Wellons

(PGP)