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()在这里是否有用。
发布于 2013-02-10 12:34:37
Python的内置map函数的行为类似于Haskell的zipWith
>>> def add(x,y): return x + y
...
>>> map(add,[1,2,3],[10,20,30])
[11, 22, 33]发布于 2013-02-10 12:35:13
def add(a, b):
return a + b
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
>> map(add, x, y)
[6, 8, 10, 12]另外,一定要查看Python内置itertools模块:http://docs.python.org/2/library/itertools.html
发布于 2013-02-10 15:33:43
这段Python代码的行为类似于您给出的zipWith'函数:
def zip_with(f, l1, l2):
if len(l1) == 0 or len(l2) == 0:
return []
else:
return [f(l1[0], l2[0])] + zip_with(f, l1[1:], l2[1:])但是,与Haskell函数相比,此函数有几个缺点。首先,它看起来不是很好,因为Python没有模式匹配语法;我们必须使用len、[0]和[1:]。第二,Python函数没有以任何方式使用惰性求值,所以zip_with将始终遍历整个列表,即使它可以提前停止。第三个是该函数对结果列表中的每个元素调用一次,而Python的递归限制约为1000个,因此如果输出列表的长度超过1000个元素,则该函数将引发异常。
第二和第三个问题可以使用生成器来解决。
https://stackoverflow.com/questions/14794676
复制相似问题