Function composition

Revision as of 07:09, 3 March 2009 by rosettacode>Spoon! (added scheme)

Create a function, compose, whose two arguments f and g, are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument x), which works like applying function f to the result of applying function g to x.

Task
Function composition
You are encouraged to solve this task according to the task description, using any language you may know.

I.e:

 compose(f, g)(x) == f( g(x) )

Reference: Function composition

Python

<lang python>compose = lambda f, g: lambda x: f( g(x) )</lang> Example use: <lang python>>>> compose = lambda f, g: lambda x: f( g(x) ) >>> from math import sin, asin >>> sin_asin = compose(sin, asin) >>> sin_asin(0.5) 0.5 >>> </lang>

Scheme

<lang scheme>(define (compose f g) (lambda (x) (f (g x))))</lang> Example use: <lang scheme>> (define (compose f g) (lambda (x) (f (g x)))) > (define sin_asin (compose sin asin)) > (sin_asin 0.5) 0.5</lang>