[英]Convert higher order function from Python to Haskell
I have the following code: 我有以下代码:
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)
Important part: Pleat takes any function and any sequence and passes the first handful of elements from that sequence into the received function as parameters. 重要部分:Pleat可以接受任何函数和任何序列,并将该序列中的前几个元素作为参数传递给接收的函数。
Is there a way to do this in Haskell or am I dreaming? 有没有办法在Haskell中做到这一点,或者我在做梦?
The type signatures below are optional: 下面的类型签名是可选的:
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
The idea is that the function is explicit about taking a list of unknown length as an argument, so it is not very type-safe. 想法是该函数明确地将未知长度的列表作为参数,因此它不是非常安全的类型。 But it is pretty much a 1-to-1 mapping of the Python code. 但这几乎是Python代码的一对一映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.