Python中的Clojure风格“线程”函数

23 投票
9 回答
3515 浏览
提问于 2025-04-16 11:35

Clojure 语言有一个叫做 "->" 的宏,它可以把每个表达式递归地作为下一个表达式的第一个参数。

这意味着我可以这样写:

(-> arg f1 f2 f3)

它的效果就像是 (shell piping):

f3(f2(f1(arg)))

我想在 Python 中实现这个功能;不过,搜索相关内容似乎非常困难!我找不到 "->",也找不到 Python 的 threading 函数!

有没有办法重载,比如说,| 操作符,这样我就可以在 Python 中这样写?

arg | f1 | f2 | f3

谢谢!

9 个回答

10

或者可以试试这个链接:https://mdk.fr/blog/pipe-infix-syntax-for-python.html。这个模块提供了一种类似于以下的语法:

  fib() | take_while(lambda x: x < 1000000)
        | where(lambda x: x % 2)
        | select(lambda x: x * x)
        | sum()
23

或者可以用下面的方式来使用reduce函数:

reduce(lambda x,f : f(x), [f1,f2,f3], arg)
16

你可以很简单地自己实现类似的功能。

def compose(current_value, *args):
    for func in args:
        current_value = func(current_value)
    return current_value

def double(n):
    return 2*n

print compose(5, double, double) # prints 20

撰写回答