【发布时间】:2013-02-10 17:30:50
【问题描述】:
Learn You a Haskell For Great Good 中关于偏函数的章节包含以下代码:
multThree :: (Num a) => a -> a -> a -> a
multThree x y z = x * y * z
ghci> let multTwoWithNine = multThree 9
ghci> multTwoWithNine 2 3
54
ghci> let multWithEighteen = multTwoWithNine 2
ghci> multWithEighteen 10
180
我目前正在使用 Python 中的 functools 库,并设法使用它复制这些函数的行为。
from functools import partial
def multThree(x,y,z):
return x * y * z
>>> multTwoWithNine = partial(multThree,9)
>>> multTwoWithNine(2,3)
>>> multWithEighteen = partial(multTwoWithNine,2)
>>> multWithEighteen(10)
180
我现在想做的一件事是看看我是否可以从同一本书的章节中复制一些更有趣的高阶函数,例如:
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
但是,我不确定如何执行此操作,或者 partial() 在这里是否有用。
【问题讨论】:
-
您应该编辑和修复您的函数,确保它们在语法上都是正确的。例如,您的第一个缺少其论点。
-
从技术上讲,您必须在任何转换中使用
partial,因为所有 Haskell 函数都是自动柯里化的,而partial模拟了柯里化函数必须部分应用的能力。或者您可以将 python 版本编写为 curried 函数,但是您必须像foo(a)(b)(c)一样调用它们。 -
次要注意:你想要“部分应用函数”而不是“部分函数”。