[英]Explicit Recursion for Determining If Duplicates in Haskell
This is a small part of a tutorial assignment where we have been asked to define a function firstly using a list comprehension and then using explicit recursion. 这只是教程任务的一小部分,我们被要求首先使用列表推导然后使用显式递归来定义函数。
- Using a list comprehension, define a function
使用列表理解,定义一个函数
duplicated :: Eq a => a -‐> [a] -‐> Bool
复制的:: 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.
它接受一个list元素和一个list,如果列表中有多个list元素,则返回True。 For example:
例如:
duplicated 10 [1,2,11,11] = False
重复10 [1,2,11,11] = False
duplicated 10 [1,2,10,11] = False
重复10 [1,2,10,11] = False
duplicated 10 [1,2,10,10] = True
重复10 [1,2,10,10] =真
For this I have the code of: 为此,我有以下代码:
duplicated::Eq a => a -> [a] -> Bool
duplicated n xs = length[x | x <- xs, x == n] > 1
But no matter how I seem to attack this, I can't figure out a way to do this with explicit recursion. 但是,无论我如何看待这种攻击,我都无法找到一种通过显式递归实现此目标的方法。
This is how to do it using explicit recursion: 这是使用显式递归执行的方法:
duplicated :: Eq a => a -> [a] -> Bool
duplicated _ [] = False
duplicated n (x:xs) = callback n xs
where callback = if x == n then elem else duplicated
Here's how it works: 运作方式如下:
n
in the list. n
。 Hence, we return False
. False
。 n
then it means that we found one element n
. n
则意味着我们找到了一个元素n
。 Hence we return elem n xs
which checks whether n
is in xs
as well. elem n xs
,它检查n
是否也在xs
中。 duplicated n xs
. duplicated n xs
。 Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.