V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
felix021
V2EX  ›  分享发现

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

  •  
  •   felix021 · 2013-07-25 16:57:11 +08:00 · 2688 次点击
    这是一个创建于 3900 天前的主题,其中的信息可能已经有所发展或是发生改变。
    英文原文: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 条回复    1970-01-01 08:00:00 +08:00
    felix021
        1
    felix021  
    OP
       2013-07-25 16:57:44 +08:00
    -。- 不知道v2ex怎么缩进代码……将就看看吧
    timonwong
        2
    timonwong  
       2013-07-25 17:33:42 +08:00
    有点F#的感觉,本质是右结合运算然后玩高阶函数还真是想的出来啊。。。
    imcj
        3
    imcj  
       2013-07-25 17:50:39 +08:00
    很shell
    kylefeng
        4
    kylefeng  
       2013-07-29 20:24:53 +08:00
    很像 Clojure 里面的 -> 和 ->> 宏。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2776 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 12:50 · PVG 20:50 · LAX 05:50 · JFK 08:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.