Reputation: 15
I'm making a function in Haskell to compute the differences between values in two lists.
For example, I have two lists:
List A = [1,2,3]
List B = [2,3,4]
Subtract the first element of A with the first element of B, subtract the second element of A with the second element of B, and so on. The result should be like this:
Result = [-1,-1,-1]
How to make this function? I tried using this but failed:
diff xs ys = [i-j | i <- xs, j <- ys, length xs == length ys]
And the result of using that wrong function is (I used list A and list B, look above):
[-1,-2,-3,0,-1,-2,1,0,-1]
Someone told me that i <- xs, j <- ys means cross-joining the elements of xs and ys, so the result is like this:
[(1-2),(1-3),(1-4),(2-2),(2-3),(2-4),(3-2),(3-3),(3-4)
Using list comprehension, and without using i <- xs, j <- ys
, complete this function:
diff :: [Int] -> [Int] -> [Int]
diff [] [] = []
diff xs [] = []
diff [] ys = []
Upvotes: 0
Views: 2762
Reputation: 352
diff :: [Int] -> [Int] -> [Int]
diff a b = map (\(p, q) -> p - q) $ zip a b
Upvotes: 1
Reputation: 1918
If you like list comprehensions, you can use an extension:
{-# LANGUAGE ParallelListComp #-}
diff a b = [p - q | p <- a | q <- b]
which is internally translated into zip
.
Upvotes: 2