compose function and functional module

家住魔仙堡 提交于 2019-12-03 06:29:43

Your implementation of compose is valid for python 3.2 as discussed in the comments above. Most of the functions of the library you gave have a python equivalent written in the documentation.

Functions such as map and filter are already implemented in python and can also be simply expressed as list comprehensions. Python has an id function returning the identity of an object (as integer), but the id function of the library can be expressed as lambda x: x.

Another modules you might find interesting are itertools and functools which has partial and reduce (which is similar to foldl but the argument order is not the same).

Here is a simple implementations of a few of them that I didn't find in the standard library:

from functools import reduce

def flip(f):
    if not callable(f):
        raise TypeError("Cannot filp a non-callable object")
    def result(*args, **kw):
        args = list(args)
        args.reverse()
        return f(*args, **kw)
    return result

def ilast(i):
    return reduce(lambda _, x: x, i)

def iscanl(f, v, seq):
    yield v
    for a in seq:
        v = f(v, a)
        yield v

def scanl(*args, **kw):
    return list(iscanl(*args, **kw))

def foldl(*args, **kw):
    return ilast(iscanl(*args, **kw))
# Or using reduce
#def foldl(f, v, seq):
#    return reduce(f, seq, v)

def iscanr_reverse(f, v, seq):
    return iscanl(flip(f), v, seq)

def scanr(*args, **kw):
    result = list(iscanr_reverse(*args, **kw))
    result.reverse()
    return result

def foldr(*args, **kw):
    return ilast(iscanr_reverse(*args, **kw))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!