EdvardM
9/14/2018 - 9:01 PM

Just a simply utility to apply sequence of functions, applying each in turn to return value of previous application

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))