我正在尝试比较haskell中两个列表的相同索引处的元素.如果两个元素在同一个索引上相等,那么我必须返回该索引.我知道如何使用filter和zip比较两个函数,但我的函数返回值而不是索引.
compare l1 l2 = map fst . filter (\(x,y) -> x == y) $ zip l1 l2
Run Code Online (Sandbox Code Playgroud)
当我用ghci运行时,我有
compare [1,2,3,4,5] [1,2,3,7,8,9,11,5]
[1,2,3]
Run Code Online (Sandbox Code Playgroud)
我想[0,1,2]改为.任何人都可以给我提示如何解决这个问题吗?
您可以使用zip3和[0..]包含索引作为大小为3的元组的第一项:
compare l1 l2 = map (\(i, _, _) -> i) . filter (\(_, x,y) -> x == y) $ zip3 [0..] l1 l2
Run Code Online (Sandbox Code Playgroud)
列表理解使Chad Gilbert的回答更加清晰.
compare l1 l2 = [i | (i, x, y) <- zip3 [0..] l1 l2, x == y]
Run Code Online (Sandbox Code Playgroud)