Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
15
Task/First-class-functions/Python/first-class-functions-1.py
Normal file
15
Task/First-class-functions/Python/first-class-functions-1.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
>>> # Some built in functions and their inverses
|
||||
>>> from math import sin, cos, acos, asin
|
||||
>>> # Add a user defined function and its inverse
|
||||
>>> cube = lambda x: x * x * x
|
||||
>>> croot = lambda x: x ** (1/3.0)
|
||||
>>> # First class functions allow run-time creation of functions from functions
|
||||
>>> # return function compose(f,g)(x) == f(g(x))
|
||||
>>> compose = lambda f1, f2: ( lambda x: f1(f2(x)) )
|
||||
>>> # first class functions should be able to be members of collection types
|
||||
>>> funclist = [sin, cos, cube]
|
||||
>>> funclisti = [asin, acos, croot]
|
||||
>>> # Apply functions from lists as easily as integers
|
||||
>>> [compose(inversef, f)(.5) for f, inversef in zip(funclist, funclisti)]
|
||||
[0.5, 0.4999999999999999, 0.5]
|
||||
>>>
|
||||
59
Task/First-class-functions/Python/first-class-functions-2.py
Normal file
59
Task/First-class-functions/Python/first-class-functions-2.py
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
'''First-class functions'''
|
||||
|
||||
from math import (acos, cos, asin, sin)
|
||||
from inspect import signature
|
||||
|
||||
|
||||
# main :: IO ()
|
||||
def main():
|
||||
'''Composition of several functions.'''
|
||||
|
||||
pwr = flip(curry(pow))
|
||||
|
||||
fs = [sin, cos, pwr(3.0)]
|
||||
ifs = [asin, acos, pwr(1 / 3.0)]
|
||||
|
||||
print([
|
||||
f(0.5) for f in
|
||||
zipWith(compose)(fs)(ifs)
|
||||
])
|
||||
|
||||
|
||||
# GENERIC FUNCTIONS ------------------------------
|
||||
|
||||
|
||||
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
|
||||
def compose(g):
|
||||
'''Right to left function composition.'''
|
||||
return lambda f: lambda x: g(f(x))
|
||||
|
||||
|
||||
# curry :: ((a, b) -> c) -> a -> b -> c
|
||||
def curry(f):
|
||||
'''A curried function derived
|
||||
from an uncurried function.'''
|
||||
return lambda a: lambda b: f(a, b)
|
||||
|
||||
|
||||
# flip :: (a -> b -> c) -> b -> a -> c
|
||||
def flip(f):
|
||||
'''The (curried or uncurried) function f with its
|
||||
two arguments reversed.'''
|
||||
if 1 < len(signature(f).parameters):
|
||||
return lambda a, b: f(b, a)
|
||||
else:
|
||||
return lambda a: lambda b: f(b)(a)
|
||||
|
||||
|
||||
# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
|
||||
def zipWith(f):
|
||||
'''A list constructed by zipping with a
|
||||
custom function, rather than with the
|
||||
default tuple constructor.'''
|
||||
return lambda xs: lambda ys: [
|
||||
f(a)(b) for (a, b) in zip(xs, ys)
|
||||
]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue