(require 'stdlib) (define (f x) (* 2 x)) (define (g x) (+ x 1)) (define (h x) (* x x)) (define (compose-1 #!rest fns) (let ((fns. (reverse fns))) (lambda (#!rest arg) (reduce funcall (apply (first fns.) arg) (rest fns.))))) ;; alternative (define (compose-2 . fs) (if (null fs) identity (lambda (x) ((apply compose-2 (rest fs)) ((first fs) x))))) (define composite (compose-1 f g h)) (dolist (test '((0 2) (1 4) (2 10) (3 20) (4 34) (5 52) (10 202))) (printf "f.g.h(%s) = %s, expected %s\n" (car test) (funcall composite (car test)) (cadr test))) ;;> I often implement data transformations that are modeled ;;> on sequenced steps of processes: a -> b -> c -> d -> e ... ;;> ;;> It is easy to create and debug each transformation step, ;;> as in (defun a2b (in) ..., but then I end up with the ;;> final combined transformation as: ;;> (e2f (d2e (c2d (b2c (a2b in))))) ;;> that looks kind of weird. ;;> ;;> Is there a better lisp idiom for a chain of transformations? ;;I have a functional-composition utility that I use a lot: ;; (funcall (compose #'e2f #'d2e #'c2d #'b2c #'a2b) in) ;;A simple implementation would be: ;; (defun compose (&rest functions) ;; (let ((functions (reverse functions))) ;; (lambda (&rest args) ;; (reduce #'funcall (rest functions) ;; :initial-value (apply (first functions) args))))) ;;It's also nice to have a MULTIPLE-VALUE-COMPOSE, so that: ;; (multiple-value-call a ;; (multiple-value-call b ;; (multiple-value-call c ;; (apply d args)))) ;;Is the same as: ;; (apply (multiple-value-compose a b c d) args) ;;And to have compiler-macros that transform things like: ;; (funcall (compose #'a #'b #'c #'d) in) ;;to: ;; (funcall (lambda (#:g0) (a (b (c (d #:g0))))) in) ;;So that you don't lose efficiency when the call to COMPOSE is just ;;syntactic sugar (as above).