Skip to content

Instantly share code, notes, and snippets.

@edvardm
Last active June 18, 2019 08:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save edvardm/ba8e6e750e5326363dfd58541ce2a9fb to your computer and use it in GitHub Desktop.
Just a simply utility to apply sequence of functions, applying each in turn to return value of previous application
def mapply(init, *funs, stop=lambda x: x is None):
"""
Apply list of funs from first to last, stopping when encountering first
return value of None.
Args:
init (Any): initial value
*funs (*Callable[..., Any]): List of functions to apply
Keyword args:
stop (Callable[..., Any]): predicate function which specifies end condition
for evaluation chain
Return:
funs[n-1](funs[n-2](..funs[0](init))), given all n-1 first calls did not return None
"""
if not funs or stop(init):
return init
return mapply(funs[0](init), *funs[1:], stop=stop)
# Examples
def mul2(x):
return 2*x
def div2(x):
return x/2
def prettify(x):
return f'Number is {x:d}'
def inc(x):
return x+1
# => ((2*4) + 1) / 2 => 4.5
print(mapply(4, mul2, inc, div2))
print(mapply(None, lambda x: 3*x, inc, div2)) # => None
# => (2*3) => 'Number is 6'
print(mapply(3, mul2, prettify))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment