我想编写一个多态函数,它输入两个列表并告诉我这两个列表是否包含公共(public)元素。我尝试编写这个函数如下:
overlaps :: (Eq a) => [a] -> [a] -> Bool
overlaps x:xs y:ys
| x `is_element_of` ys = True
| otherwise = False
哪里
is_element_of :: (Eq a) => a -> [a] -> Bool
is_element_of e list = case list of
[] -> False
x: xs -> e == x || e `is_element_of` xs
但是这不起作用...是否可以对两个列表进行模式匹配?这是编写此函数的可能方法吗?
最佳答案
您的函数 is_elem_of
已作为 elem
存在于 Data.List
包中。使用它,overlaps
很容易编写。
overlaps [] _ = False
overlaps (x:xs) ys = x `elem` ys || overlaps xs ys
正如您所知,列表上的模式匹配是可能的。如果您想在列表上编写不进行模式匹配的函数,可以使用 foldr
函数。
overlaps xs ys = foldr (\x acc -> x `elem` ys || acc) False xs
关于haskell - 书写重叠功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37040868/