我想编写一个输入两个列表的多态函数,并告诉我这两个列表是否包含一个公共元素。我写这个函数的尝试如下:
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
然而这不起作用......是否可以对两个列表进行模式匹配?这是写这个函数的可能方法吗?
答案 0 :(得分:2)
您的is_elem_of
个功能Data.List
已作为elem
存在。使用它,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
答案 1 :(得分:0)
我想你会想要这样的东西(未经测试):
overlaps :: (Eq a) => [a] -> [a] -> Bool
overlaps [] _ = False
overlaps _ [] = False
overlaps (x:xs) list = x `myelem` list || overlaps xs list
myelem :: (Eq a) => a -> [a] -> Bool
myelem _ [] = False
myelem x (y:ys) = x == y || myelem x ys
使用模式匹配方法的AFAIK更具惯用性。