我在Haskell中创建一个函数来计算两个列表中值之间的差异。
例如,我有两个列表:
List A = [1,2,3]
List B = [2,3,4]
用B的第一个元素减去A的第一个元素,用B的第二个元素减去A的第二个元素,依此类推。结果应该是这样的:
Result = [-1,-1,-1]
如何制作此功能?我尝试使用它但失败了:
diff xs ys = [i-j | i <- xs, j <- ys, length xs == length ys]
使用该错误函数的结果是(我使用列表A和列表B,看上面):
[-1,-2,-3,0,-1,-2,1,0,-1]
有人告诉我,我&lt; - xs,j&lt; - ys表示交叉连接xs和ys的元素,所以结果是这样的:
[(1-2),(1-3),(1-4),(2-2),(2-3),(2-4),(3-2),(3-3),(3-4)
使用列表理解,而不使用i <- xs, j <- ys
,完成此功能:
diff :: [Int] -> [Int] -> [Int]
diff [] [] = []
diff xs [] = []
diff [] ys = []
答案 0 :(得分:2)
如果您喜欢列表推导,可以使用an extension:
{-# LANGUAGE ParallelListComp #-}
diff a b = [p - q | p <- a | q <- b]
内部翻译为zip
。
答案 1 :(得分:1)
diff :: [Int] -> [Int] -> [Int]
diff a b = map (\(p, q) -> p - q) $ zip a b