Function composition: Difference between revisions

From Rosetta Code
Content added Content deleted
(Function composition with Python example.)
 
(added scheme)
Line 16: Line 16:
0.5
0.5
>>> </lang>
>>> </lang>

=={{header|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>

Revision as of 07:09, 3 March 2009

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

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.

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>