简体   繁体   English

确定Haskell中是否重复的显式递归

[英]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. 这只是教程任务的一小部分,我们被要求首先使用列表推导然后使用显式递归来定义函数。

  1. 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: 运作方式如下:

  1. If the list is empty then it means that we haven't found even one element n in the list. 如果列表为空,则意味着在列表中甚至没有找到一个元素n Hence, we return False . 因此,我们返回False
  2. Otherwise, if the current element of the list is 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中。
  3. Otherwise, we recursively call duplicated n xs . 否则,我们递归地调用duplicated n xs

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM