这是教程作业的一小部分,其中要求我们首先使用列表理解然后使用显式递归来定义函数。
- Using a list comprehension, define a function
duplicated :: Eq a => a -‐> [a] -‐> Bool
that takes a list element and a list and returns True if there is more than one copy of the list element in the list. For example:
duplicated 10 [1,2,11,11] = False
duplicated 10 [1,2,10,11] = False
duplicated 10 [1,2,10,10] = True
为此,我有以下代码:
duplicated::Eq a => a -> [a] -> Bool
duplicated n xs = length[x | x <- xs, x == n] > 1
但无论我如何攻击这个问题,我都无法找到一种通过显式递归来做到这一点的方法。
最佳答案
这是使用显式递归的方法:
duplicated :: Eq a => a -> [a] -> Bool
duplicated _ [] = False
duplicated n (x:xs) = callback n xs
where callback = if x == n then elem else duplicated
其工作原理如下:
- 如果列表为空,则意味着我们在列表中甚至没有找到
n
元素。因此,我们返回False
。 - 否则,如果列表的当前元素是
n
,则表示我们找到了一个元素n
。因此,我们返回elem n xs
来检查n
是否也在xs
中。 - 否则,我们会递归调用
重复的 n xs
。
希望有帮助。
关于haskell - Haskell 中用于确定是否重复的显式递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090969/