2011-09-18

SICP Exercise 1.42: Composing Functions

Let f and g be two one-argument functions. The composition f after g is defined to be the function x→f(g(x)). Define a procedure compose that implements composition. For example, if inc is a procedure that adds 1 to its argument,
((compose square inc) 6)
49
After the last exercise, this one is nice and easy. All the procedure compose needs to do is to produce a lambda expression that takes a single parameter, applies g to that parameter and then applies f to the result of that:
(define (compose f g)
  (lambda (x) (f (g x))))
And just to confirm it works:
> ((compose square inc) 6)
49

No comments:

Post a Comment