Searching through list

后端 未结 4 844
日久生厌
日久生厌 2021-01-26 14:47

I\'ve been trying to define a function which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list.

I have t

4条回答
  •  心在旅途
    2021-01-26 15:24

    Here is another version:

    once x = not . (\xs -> null xs || x `elem` tail xs) . dropWhile (/= x)
    
    --lambda hater version
    import Control.Applicative
    once x = not . ((||) <$> null <*> (elem x).tail) . dropWhile (/= x)
    

    Of course it can't deal with infinite lists that contain zero or one x, but at least it terminates in case of more than one occurrence of x.

提交回复
热议问题