I'm trying to compare element at the same index of two lists in haskell. If the two elements are equal an at the same index then I have to return that index. i know how to compare two function using filter and zip, but my function return the value instead of the index.
compare l1 l2 = map fst . filter (\(x,y) -> x == y) $ zip l1 l2
When I run it with ghci i have
compare [1,2,3,4,5] [1,2,3,7,8,9,11,5]
[1,2,3]
I want to have [0,1,2] instead. Can anybody give me hints how to go about this?
You could use zip3 and [0..] to include an index as the first item of a tuple of size three:
compare l1 l2 = map (\(i, _, _) -> i) . filter (\(_, x,y) -> x == y) $ zip3 [0..] l1 l2
A list comprehension makes Chad Gilbert's answer a little cleaner.
compare l1 l2 = [i | (i, x, y) <- zip3 [0..] l1 l2, x == y]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With