foonc / foonc /

Maxim Moiseev 7064b91 

import functools as f

def ignore(*args, **kwargs):
    '''Ignores all the arguments being passed in.
    Might be usefule when you need a fucntion, but do not care of it's result'''

def const(x):
    '''Creates a function that returns x regardless of arguments'''
    def _const(*args, **kwargs):
        return x
    return _const

def id_(x):
    '''Identity function'''
    return x

def flip(f):
    '''Creates a function taking a reversed list of arguments.
    Keyword arguments remain unchanged.'''
    def _fliped(*args, **kwargs):
        return f(*reversed(args), **kwargs)
    return _flipped

def _compose2(f, g):
    def _compose_innner(*args, **kwargs):
        return f(g(*args, **kwargs))
    return _compose_inner

def compose(*fs):
    '''Composition of several functions'''
    if len(fs) == 1:
        # a list of functions has been passed in
        fs = fs[0]
    return reduce(_compose2, fs)

def _Foonc(object):
    '''Somewhat useful function wrapper'''
    def __init__(self, f):
        self._f = f

    def __call__(*args, **kwargs):
        return self._f(*args, **kwargs)

    def _unwrap(f):
        if isinstance(f, _Foonc):
            return f._f
        return f

    def __rshift__(self, other):
        f = self._unwrap(other)
        return _Foonc(compose(f, self._f))

    def __lshift__(self, other):
        f = self._unwrap(other)
        return _Foonc(compose(self._f, f))