haskell - 书写重叠功能

标签 haskell pattern-matching

我想编写一个多态函数,它输入两个列表并告诉我这两个列表是否包含公共(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/

相关文章:

haskell - 寻找特殊 map 功能的名称

list - 在 Haskell 中处理列表列表

java - Matcher.group 抛出 IndexOutOfBoundsException 异常

Python 使用正则表达式捕获字符串中的特定模式

templates - Play 2.0 模板中 object.member 的模式匹配

haskell - 为什么运算符/函数转换不可逆?

templates - 如何在 Yesod 中导入莎士比亚模板?

bash - 使用 AWK 递归查找

Haskell:为什么模式匹配中不允许使用++?

haskell - 简单的随机数生成