Function composition: Difference between revisions

m
→‎Python Multiple composition: Updated primitive, tidied.
m (→‎JavaScript ES6 - Multiple composition: Updated primitive, tidied.)
m (→‎Python Multiple composition: Updated primitive, tidied.)
Line 2,597:
{{Works with|Python|3}}
<lang python>from functools import reduce
from numbersmath import Numbersqrt
import math
 
 
def composeListcompose(*fs):
'''Composition, from right to left,
of aan seriesarbitrary number of functions.'''
)'''
def go(f, g):
return lambda x: reducef(g(x))
 
return reduce(go, fs, lambda x: x)
 
 
# ------------------------- TEST -------------------------
def main():
'''TestComposition of three functions.'''
 
f = composeListcompose([
lambda x: x / 2half,
succ,
math.sqrt
])
 
print(
Line 2,615 ⟶ 2,625:
 
 
# GENERIC FUNCTIONS ----------------------- GENERAL ------------------------
def succhalf(xn):
return n / x2
 
 
def succ(n):
# composeList :: [(a -> a)] -> (a -> a)
return 1 + n
def composeList(fs):
'''Composition, from right to left,
of a series of functions.'''
return lambda x: reduce(
lambda a, f: f(a),
fs[::-1],
x
)
 
 
# succ :: Enum a => a -> a
def succ(x):
'''The successor of a value. For numeric types, (1 +).'''
return 1 + x if isinstance(x, Number) else (
chr(1 + ord(x))
)
 
 
Line 2,641 ⟶ 2,638:
{{Out}}
<pre>1.618033988749895</pre>
 
 
=== composition via operator overloading===
9,655

edits