Function composition: Difference between revisions
(added scheme) |
|||
Line 6: | Line 6: | ||
Reference: [[wp:Function composition (computer science)|Function composition]] |
Reference: [[wp:Function composition (computer science)|Function composition]] |
||
=={{header|ALGOL 68}}== |
|||
{{trans|Python}} |
|||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
|||
Note: Returning <code>PROC (REAL x)REAL: f1(f2(x))</code> from a function apparently |
|||
violates standard '''ALGOL 68''''s scoping rules. [[ALGOL 68G]] warns about this during |
|||
parsing, and then rejects during runtime. |
|||
<lang algol>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed # |
|||
# As a procedure for real to real functions # |
|||
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x)); |
|||
OP (F,F)F O = compose; # or an OPerator that can be overloaded # |
|||
# Example use: # |
|||
F sin arc sin = compose(sin, arc sin); |
|||
print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</lang> |
|||
Output: |
|||
<pre> |
|||
+.500000000000000e +0 +.500000000000000e +0 |
|||
</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
<lang python>compose = lambda f, g: lambda x: f( g(x) )</lang> |
<lang python>compose = lambda f, g: lambda x: f( g(x) )</lang> |
Revision as of 10:44, 3 March 2009
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
ALGOL 68
Note: Returning PROC (REAL x)REAL: f1(f2(x))
from a function apparently
violates standard ALGOL 68's scoping rules. ALGOL 68G warns about this during
parsing, and then rejects during runtime.
<lang algol>MODE F = PROC(REAL)REAL; # ALGOL 68 is strong typed #
- As a procedure for real to real functions #
PROC compose = (F f, g)F: (REAL x)REAL: f(g(x));
OP (F,F)F O = compose; # or an OPerator that can be overloaded #
- Example use: #
F sin arc sin = compose(sin, arc sin); print((sin arc sin(0.5), (sin O arc sin)(0.5), new line))</lang> Output:
+.500000000000000e +0 +.500000000000000e +0
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>