V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
felix021

Pipe: Infix syntax for Python //为Python增加中缀语法

  •  
  •   felix021 · Jul 25, 2013 · 3198 views
    This topic created in 4671 days ago, the information mentioned may be changed or developed.
    英文原文:http://dev-tricks.net/pipe-infix-syntax-for-python
    翻译版本:http://blog.csdn.net/lanphaday/article/details/6287114

    刚刚才发现的这东西,觉得挺有意思的,一个简单的例子是:

    >>> from pipe import *
    >>> [1, 2, 3, 4, 5] | add
    15

    复杂一点的,例如求Fibonacci数列前100项的和:


    from pipe import *

    def fib():
    a, b = 1, 0
    while True:
    yield a
    a, b = a + b, a

    print enumerate(fib()) | take_while(lambda (i, x): i < 100) | select(lambda (i, x): x) | add

    除了add之外,作者还实现了常见的方法,例如

    select: 类似于 map
    where: 类似于 filter,后者
    sort/reverse/max/min/take/tail/skip ...

    这个库在pypi里有:http://pypi.python.org/pypi/pipe

    看了下核心实现非常简单,就是利用了 __ror__ 和 decorator:

    class Pipe:
    def __init__(self, function):
    self.function = function

    def __ror__(self, other):
    return self.function(other)

    def __call__(self, *args, **kwargs):
    return Pipe(lambda x: self.function(x, *args, **kwargs))

    @Pipe
    def add(x):
    return sum(x)
    4 replies    1970-01-01 08:00:00 +08:00
    felix021
        1
    felix021  
    OP
       Jul 25, 2013
    -。- 不知道v2ex怎么缩进代码……将就看看吧
    timonwong
        2
    timonwong  
       Jul 25, 2013
    有点F#的感觉,本质是右结合运算然后玩高阶函数还真是想的出来啊。。。
    imcj
        3
    imcj  
       Jul 25, 2013
    很shell
    kylefeng
        4
    kylefeng  
       Jul 29, 2013
    很像 Clojure 里面的 -> 和 ->> 宏。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2783 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:40 · PVG 09:40 · LAX 18:40 · JFK 21:40
    ♥ Do have faith in what you're doing.