File: functional.py

package info (click to toggle)
python-enthoughtbase 3.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 960 kB
  • ctags: 1,034
  • sloc: python: 6,104; makefile: 9; sh: 5
file content (28 lines) | stat: -rw-r--r-- 747 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'Non-standard higher-order functions'

def partial(f, *a, **k): # (2.5 provides this)
    # Don't mutate 'a' or 'k' since each call to 'g' shares them
    def g(*b, **l):
        m = k.copy()
        m.update(l)
        return f(*(a + b), **m)
    return g

def compose(*fs):
    ''' ``compose(f,g,...,h)(*args, **kw) == f(g(...(h(*args, **kw))))``

        >>> compose(len, str)(100)
        3
        >>> compose(len, str, len, str)(1234567890)
        2
        >>> compose()(1)
        1
        >>> map(compose(sum, range, len), ['foo', 'asdf', 'wibble'])
        [3, 6, 15]
    '''

    if len(fs) == 0:
        return lambda x: x

    binary_compose = lambda f,g: lambda *args, **kw: f(g(*args, **kw))
    return reduce(binary_compose, fs)