Reputation: 47
Here is the problem I want to solve:
The two lists [1,2,3,4] [2,2,3,4]
is to become [2,3,4]
, because elements at index position zero are not equal. So elements are compared for equality with respect to their index. You can assume equal length lists as input.
So I created a function that solved this with recursion:
oneHelper :: (Eq t) => [t] -> [t] -> [t]
oneHelper [] [] = []
oneHelper (x:xs) (y:ys) = if x == y then [x] ++ oneHelper xs ys
else oneHelper xs ys
Then I tried to solve it with list comprehension like this:
test a b = [x | x <- a, y <- b, x == y]
which just gives me [2,2,3,4]
with example input above used. I feel like there is a neat way of solving this with a list comprehension, or just a more neat way than the solution I came up with in general, but I am struggling to reach that solution. Does anyone see something better than what I did for the problem?
Thanks
Upvotes: 1
Views: 725
Reputation: 477170
If you use the two generators, you will iterate over all possible combinations of the elements in the first list (a
) and second list (b
).
You probably want to use zip :: [a] -> [b] -> [(a, b)]
here where we iterate over the two lists concurrently:
test a b = [x | (x, y) <- zip a b, x == y]
Upvotes: 1