将高阶函数从Python转换为Haskell
我有以下代码:
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
if __name__=="__main__":
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
重要的部分是:Pleat这个东西可以接收任何函数和任何序列,然后把那个序列中的前几个元素作为参数传给接收到的函数。
在Haskell中有没有办法做到这一点,还是我在做梦呢?
1 个回答
6
下面的类型签名是可选的:
stagger :: [a] -> Int -> [[a]] stagger l w | length l >= w = take w l : stagger (tail l) w | otherwise = [] pleat :: ([a] -> b) -> [a] -> Int -> [b] pleat f l w = map f $ stagger l w main = do print $ pleat (\[x, y] -> x+y) [0..9] 2 print $ pleat (\[x, y, z] -> x*y/z) [3..12] 3 print $ pleat (\[x] -> "~" ++ show x ++ "~") [0..9] 1 print $ pleat (\[a, b, x, y] -> a+b == x+y) [3, 2, 4, 1, 5, 0, 9, 9, 0] 4
这里的意思是,这个函数明确表示它会接收一个长度不确定的列表作为参数,所以它在类型安全性上不是特别高。不过,这基本上和Python代码是一一对应的。