简体   繁体   中英

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

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

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. Hence, we return False .
  2. Otherwise, if the current element of the list is n then it means that we found one element n . Hence we return elem n xs which checks whether n is in xs as well.
  3. Otherwise, we recursively call duplicated n xs .

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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