Haskell: How to put multiple instances in the same module?

前端 未结 4 2074
独厮守ぢ
独厮守ぢ 2021-01-13 21:23

Let\'s say that I have the following code:

import Data.List.Ordered

data Person = Person String String
     deriving (Show, Eq)

main :: IO ()
main = print          


        
4条回答
  •  自闭症患者
    2021-01-13 21:44

    The newtype method would be:

    newtype ByFirstname = ByFirstname { unByFirstname :: Person }
    
    instance Ord ByFirstname where
      -- pattern matching on (ByFirstname (Person xFirst _)) etc
      compare [...] = [...]
    
    newtype ByLastname = ByLastname { unByLastname :: Person }
    
    instance Ord ByLastname where
      -- as above
    

    Then the sorting function would be something like:

    sortFirstname = map unByFirstname . sort . map ByFirstname
    

    and similarly for ByLastname.


    A better way is to use sortBy, compare and on, with functions for retrieving the first and last names. i.e.

    sortFirstname = sortBy (compare `on` firstName)
    

    (On that note, it might be worth using a record type for Person, i.e. data Person = Person { firstName :: String, lastName :: String }, and one even gets the accessor functions for free.)

提交回复
热议问题