Possible Duplicate:
Searching through list
I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.
Main> once [2,3,2,4] 2
False
Main> once [1..100] 2
True
And here is my current code:
once :: Int -> [Int] -> Bool
once 开发者_Python百科x [] = False
once x (y:ys) = (x==y) || (once x ys)
It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false. Need help with this, thanks!
There are many possibilities doing that. If you know that the list is finite, you could say:
once x xs = length (filter (==x) xs) == 1
(If it's not finite, there is no solution.)
By the way, you had it almost in your solution, you just replace
|| (once x ys)
with
&& (x `notElem` ys)
Try this:
- write a function
once
, that scans the list until it finds the element for the first time or the end of the list. In the latter case it returnsFalse
, else it callsonce'
on the rest of the list and returns the result. once'
does essentially the same asonce
, but returnsFalse
, if the element is found andTrue
, if not.
精彩评论