python - 在 python toolz 中柯里化(Currying) merge_with

标签 python currying toolz

我希望能够柯里化(Currying)merge_with:

merge_with 按我的预期工作

>>> from cytoolz import curry, merge_with
>>> d1 = {"a" : 1, "b" : 2}
>>> d2 = {"a" : 2, "b" : 3}
>>> merge_with(sum, d1, d2)
{'a': 3, 'b': 5}

在一个简单的函数上,curry 按我的预期工作:

>>> def f(a, b):
...     return a * b
... 
>>> curry(f)(2)(3)
6

但我无法“手动”制作 merge_with 的柯里化(Currying)版本:

>>> curry(merge_with)(sum)(d1, d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> curry(merge_with)(sum)(d1)(d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

预柯里化(Currying)版本有效:

>>> from cytoolz.curried import merge_with as cmerge
>>> cmerge(sum)(d1, d2)
{'a': 3, 'b': 5}

我的错误在哪里?

最佳答案

这是因为 merge_withdicts 作为位置参数:

merge_with(func, *dicts, **kwargs)

所以 f 是唯一的强制参数,对于空的 *args 你会得到一个空字典:

>>> curry(merge_with)(sum)  # same as merge_with(sum)
{}

所以:

curry(f)(2)(3)

相当于

>>> {}(2)(3)
Traceback (most recent call last):
...
TypeError: 'dict' object is not callable

您必须明确并定义助手

def merge_with_(f):
    def _(*dicts, **kwargs):
        return merge_with(f, *dicts, **kwargs)
    return _

可以根据需要使用:

>>> merge_with_(sum)(d1, d2)
{'a': 3, 'b': 5}

或者:

def merge_with_(f, d1, d2, *args, **kwargs):
    return merge_with(f, d1, d2, *args, **kwargs)

两者都可以

>>> curry(merge_with_)(sum)(d1, d2)
{'a': 3, 'b': 5}

和:

>>> curry(merge_with_)(sum)(d1)(d2)
{'a': 3, 'b': 5}

关于python - 在 python toolz 中柯里化(Currying) merge_with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47635640/

相关文章:

python - 类型检查动态添加的属性

python - 使用 joblib 的 sklearn 转储模型,转储多个文件。哪个是正确的模型?

python - Pandas:缩短多列的字符串

python - toolz.thread_first() 和 toolz.thread_last() 的目的是什么?

python - 将序列变成列表的函数

Python - 将元组应用于功能工具 z.pipe 中的函数

python - Flask 中的通用端点

scala - 如何将代码块传递给函数?

swift - 柯里化(Currying)所有 swift 函数参数,但不调用该函数

python - 在 Python lambda 中柯里化(Currying)