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
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:
n
in the list. Hence, we return False
. 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. 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.