My Mailbag
February 7, 2020
Here is our version of russian multiplication:
(define (mult left right) (let loop ((left left) (right right) (prod 0)) (cond ((= left 1) (+ prod right)) ((odd? left) (loop (quotient left 2) (* right 2) (+ prod right))) (else (loop (quotient left 2) (* right 2) prod)))))
> (mult 7 13) 91 > (mult 13 7) 91
And here is the new compose
function:
(define (compose . fns) (let comp ((fns fns)) (cond ((null? fns) (lambda (x) x)) ; identity function ((null? (cdr fns)) (car fns)) (else (lambda args (call-with-values (lambda () (apply (comp (cdr fns)) args)) (car fns)))))))
> ((compose) (+ 1 4)) 5 > ((compose add1) 4) 5 > ((compose add1 double) 2) 5
You can run the program at https://ideone.com/5g33iW.
Should compose with no arguments return a function like (lambda args (apply values args))?
Here’s a solution in Python.
Output: