Commits

Maxim Moiseev committed 25b91b5

initial version of foonc. no tests yet

  • Participants
  • Parent commits 4e3d290

Comments (0)

Files changed (1)

File src/foonc.py

+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'''
+    pass
+
+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 _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)
+
+    @staticmethod
+    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))
+