2024-05-23 21:11:53 发布
网友
我正在学习一些函数式编程,并在看toolz。在我看来,compose、pipe、thread_first和thread iu last之间的区别似乎非常微妙或根本不存在。这些功能的预期不同用例是什么?在
compose与thread_*和{}
compose
thread_*
compose本质上是一个function compostion(∘)。它的主要目标是将不同的函数组合成可重用的块。应用程序的顺序与参数的顺序相反,因此compose(f, g, h)(x)是f(g(h(x)))(与(f∘g)(x)是f(g(x))。在
compose(f, g, h)(x)
f(g(h(x)))
thread_*和{}是关于使用可重用块来创建单个数据流的。只有延迟操作才能延迟执行,但块是固定的。应用程序的顺序与参数的顺序相同,因此pipe(x, f, g, h)是h(g(f(x)))。
pipe(x, f, g, h)
h(g(f(x)))
compose对thread_*。在
{{cd2}不允许额外的参数。如果不使用curry,compose只能与一元函数一起使用。在
相比之下,thread_可以与更高的实数函数一起使用,包括常用的高阶函数:
thread_
thread_last( range(10), (map, lambda x: x + 1), (filter, lambda x: x % 2 == 0) )
与compose相同的事情,您需要curry:
或者
from toolz import curried pipe( range(10), curried.map(lambda x: x + 1), curried.filter(lambda x: x % 2 == 0) )
thread_first与thread_last。在
thread_first
thread_last
thread_first将管道参数放在函数的第一个位置。在
thread_last将管道参数放在函数的最后一个位置。在
例如
>>> from operator import pow >>> thread_last(3, (pow, 2)) # pow(2, 3) 8 >>> thread_first(3, (pow, 2)) # pow(3, 2) 9
在实践中(忽略一些形式主义),这些函数通常是可互换的,尤其是与functools.partial/toolz.curry和一些{}表达式组合使用时,根据上下文的不同,使用一个比另一个更方便。在
functools.partial
toolz.curry
例如,对于内置的高阶函数,如map或functools.reduce,thread_last是一个自然的选择。如果您想在多个地方重用一段代码,那么使用compose(h, g, f),而不是添加函数包装器def fgh(x) pipe(x, f, g, h)。等等。在
map
functools.reduce
compose(h, g, f)
def fgh(x) pipe(x, f, g, h)
compose
与thread_*
和{compose
本质上是一个function compostion(∘)。它的主要目标是将不同的函数组合成可重用的块。应用程序的顺序与参数的顺序相反,因此compose(f, g, h)(x)
是f(g(h(x)))
(与(f∘g)(x)是f(g(x))。在thread_*
和{pipe(x, f, g, h)
是h(g(f(x)))
。compose
对thread_*
。在{{cd2}不允许额外的参数。如果不使用curry,
compose
只能与一元函数一起使用。在相比之下,
thread_
可以与更高的实数函数一起使用,包括常用的高阶函数:与
^{pr2}$compose
相同的事情,您需要curry:或者
thread_first
与thread_last
。在thread_first
将管道参数放在函数的第一个位置。在thread_last
将管道参数放在函数的最后一个位置。在例如
在实践中(忽略一些形式主义),这些函数通常是可互换的,尤其是与}表达式组合使用时,根据上下文的不同,使用一个比另一个更方便。在
functools.partial
/toolz.curry
和一些{例如,对于内置的高阶函数,如
map
或functools.reduce
,thread_last
是一个自然的选择。如果您想在多个地方重用一段代码,那么使用compose(h, g, f)
,而不是添加函数包装器def fgh(x) pipe(x, f, g, h)
。等等。在相关问题 更多 >
编程相关推荐