开发者

How to deal with duplicate elements in the list in Haskell [duplicate]

开发者 https://www.devze.com 2023-02-24 07:25 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Searching through list I need to write a function \'once\' which, given a list of Integers and an Integer
This question already has answers here: Closed 11 years ago.

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 returns False, else it calls once'on the rest of the list and returns the result.
  • once' does essentially the same as once, but returns False, if the element is found and True, if not.
0

精彩评论

暂无评论...
验证码 换一张
取 消