functionschemer5rs

Scheme function that return composition of functions


How to realize a function that takes as input an any number of procedures with one argument and returns another function is the composition of these procedures in Scheme.

For example:

(define (f x) (* x 2))
(define (g x) (* x 3))
(define (h x) (- x))

((comp-func f g h) 1) => -6
((comp-func f g) 1)   => 6
((comp-func h) 1)     => -1
((comp-func) 1)       => 1

Solution

  • A clean solution would be

    (define (comp-func . procs)
      (define (comp-rec arg procs)
        (if (null? procs)
            arg
            ((car procs) (comp-rec arg (cdr procs)))))
    
      comp-rec)
    

    However with this solution you need to call it like this ((comp-func f g h) 1 (list f g h)).

    Here is a solution that will work if you call it like in your examples, however it is a bit uglier because we need to use set! to change procs argument.

    (define (comp-func . procs)
      (define (comp-rec arg)
        (if (null? procs)
            arg
            (let ((proc (car procs))
                  (rest (cdr procs)))
              (set! procs rest)
              (proc (comp-rec arg)))))
    
      comp-rec)