我有一个简单的问题:

combine :: (a -> b -> c) -> [a] -> [b] -> [c]
combine f (a:as) (b:bs) =  f a b : combine f as bs
combine _  _ _      = [ ]

这是递归的。现在,我想使用列表推导来解决相同的问题:
combine f (x:xs) (y:ys) = [ f x y  | x <- (x:xs), y <- (y:ys) ]

但是我的问题是元素的组合。我只想结合x1 y1, x2 y2, xs ys ...而不是x1 y1, x1 y2, x1 ys, x2 y1, x2 y2, .....

谢谢!

最佳答案

您需要的是parallel list compehension。为了能够使用它,您需要为编译器指定ParallelListComp编译指示:

{-# LANGUAGE ParallelListComp #-}

combine :: (a -> b -> c) -> [a] -> [b] -> [c]
combine f xs ys = [ f x y | x <- xs | y <- ys ]

编译器将其还原到zipWith应用程序:
combine :: (a -> b -> c) -> [a] -> [b] -> [c]
combine f xs ys = zipWith f xs ys

实际上这就是您的功能,所以:
combine :: (a -> b -> c) -> [a] -> [b] -> [c]
combine = zipWith

关于haskell - 结合功能与列表理解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21384704/

10-09 03:30