unique elements in a haskell list

前端 未结 7 1966
有刺的猬
有刺的猬 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:57

    Algorithm in Haskell to create a unique list:

    data Foo = Foo { id_ :: Int
                   , name_ :: String
                   } deriving (Show)
    
    alldata = [ Foo 1 "Name"
              , Foo 2 "Name"
              , Foo 3 "Karl"
              , Foo 4 "Karl"
              , Foo 5 "Karl"
              , Foo 7 "Tim"
              , Foo 8 "Tim"
              , Foo 9 "Gaby"
              , Foo 9 "Name"
              ]
    
    isolate :: [Foo] -> [Foo]
    isolate [] = []
    isolate (x:xs) = (fst f) : isolate (snd f)
      where
        f = foldl helper (x,[]) xs
        helper (a,b) y = if name_ x == name_ y
                         then if id_ x >= id_ y
                              then (x,b)
                              else (y,b)
                         else (a,y:b)
    
    main :: IO ()
    main = mapM_ (putStrLn . show) (isolate alldata)
    

    Output:

    Foo {id_ = 9, name_ = "Name"}
    Foo {id_ = 9, name_ = "Gaby"}
    Foo {id_ = 5, name_ = "Karl"}
    Foo {id_ = 8, name_ = "Tim"}
    

提交回复
热议问题