unique elements in a haskell list

前端 未结 7 1949
有刺的猬
有刺的猬 2020-12-13 17:03

okay, this is probably going to be in the prelude, but: is there a standard library function for finding the unique elements in a list? my (re)implementation, for clarificat

7条回答
  •  春和景丽
    2020-12-13 17:39

    I think that unique should return a list of elements that only appear once in the original list; that is, any elements of the orginal list that appear more than once should not be included in the result.

    May I suggest an alternative definition, unique_alt:

        unique_alt :: [Int] -> [Int]
        unique_alt [] = []
        unique_alt (x:xs)
            | elem x ( unique_alt xs ) = [ y | y <- ( unique_alt xs ), y /= x ]
            | otherwise                = x : ( unique_alt xs )
    

    Here are some examples that highlight the differences between unique_alt and unqiue:

        unique     [1,2,1]          = [2,1]
        unique_alt [1,2,1]          = [2]
    
        unique     [1,2,1,2]        = [1,2]
        unique_alt [1,2,1,2]        = []
    
        unique     [4,2,1,3,2,3]    = [4,1,2,3]
        unique_alt [4,2,1,3,2,3]    = [4,1]
    

提交回复
热议问题