Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing elements at the same index

Tags:

haskell

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?

like image 525
K.U Avatar asked Aug 11 '26 00:08

K.U


2 Answers

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
like image 103
Chad Gilbert Avatar answered Aug 13 '26 22:08

Chad Gilbert


A list comprehension makes Chad Gilbert's answer a little cleaner.

compare l1 l2 = [i | (i, x, y) <- zip3 [0..] l1 l2, x == y]
like image 20
chepner Avatar answered Aug 14 '26 00:08

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!