1

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

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

"if you use the two generators, you will iterate over all possible combinations..", Thanks for the enlightenment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.