问题描述
在Clojure中,我可以执行以下操作:
In Clojure I can do something like this:
(-> path
clojure.java.io/resource
slurp
read-string)
而不是这样做:
(read-string (slurp (clojure.java.io/resource path)))
这在Clojure术语中称为线程 ,有助于消除很多括号.
This is called threading in Clojure terminology and helps getting rid of a lot of parentheses.
在Python中,如果我尝试使用map
,any
或filter
之类的功能结构,则必须将它们相互嵌套.在Python中是否有一种结构可以用来类似于Clojure中的线程(或管道)?
In Python if I try to use functional constructs like map
, any
, or filter
I have to nest them to each other. Is there a construct in Python with which I can do something similar to threading (or piping) in Clojure?
我不是要寻找功能齐全的版本,因为Python中没有宏,我只想在使用Python进行函数式编程时消除很多括号.
I'm not looking for a fully featured version since there are no macros in Python, I just want to do away with a lot of parentheses when I'm doing functional programming in Python.
编辑:我最终使用了 toolz 支持pipe
ing.
I ended up using toolz which supports pipe
ing.
推荐答案
这里是@deceze想法的简单实现(尽管,正如@Carcigenicate指出的那样,它充其量只是部分解决方案):
Here is a simple implementation of @deceze's idea (although, as @Carcigenicate points out, it is at best a partial solution):
import functools
def apply(x,f): return f(x)
def thread(*args):
return functools.reduce(apply,args)
例如:
def f(x): return 2*x+1
def g(x): return x**2
thread(5,f,g) #evaluates to 121
这篇关于是否有类似Python中Clojure的线程宏的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!