简体   繁体   中英

Name parametrized Data type

I am learning (once again) haskell and I have the following code:

import qualified Data.Map as Map

data Union = Union
    {
        father :: Int,
        mother :: Int,
        offspring :: [Int]
    }
    deriving Show

data Person = Person
    {
        uid :: Int,
        name :: String,
        parentUnion :: Maybe Union,
        unions :: [Union]
    }
    deriving Show

family :: Map.Map Int Person
family = Map.fromList []

addPerson :: (Map.Map Int Person) -> Person -> (Map.Map Int Person)
addPerson family person
    | Map.member puid family = error "Repeated id"
    | otherwise = Map.insert puid person family
    where puid = uid person

Now with more functions, I will have quite a lot of Map.Map Int Person types. Is there a way to define a type Family which is the same as Map.Map Int Person , so I could spell:

addPerson :: Family -> Person -> Family

My naive approach:

data Family = Map.Map Int Person

gives me a nice error:

Qualified constructor in data type declaration

Yes. To create "type synonyms" like that, just use type instead of data :

type Family = Map.Map Int Person

This makes Family exactly the same as writing out Map.Map Int Person . In fact, error messages will sometimes write out the full version instead of the synonym, so be ready for that.

Another option is to use a newtype :

newtype Family = Family (Map.Map Int Person)

The difference is that the newtype version is, like the name says, a new type: it is not directly compatible with Map.Map Int Person . If you try to use one where the other is expected, you will get an error. This is probably less useful for your example, but can be used to encode additional invariants in your types.

The newtype version is almost identical to a data construction:

data Family = Family (Map.Map Int Person)

It also introduces a new constructor Family which takes a single argument. However, unlike a normal data type, this only exists at compile time ; the runtime representations of Family and Map.Map Int Person would still be exactly the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM