简体   繁体   中英

Confusion about “type” and “data” in haskell

data MoneyAmount = Amount Float Currency
     deriving (Show, Eq)
data Currency = EUR | GBP | USD | CHF 
     deriving (Show, Eq)     
type Account = (Integer, MoneyAmount)

putAmount :: MoneyAmount -> Account -> Account
putAmount mon acc = undefined

I need to write a function that adds money to an account (display error if money added is wrong currency in account).

I know how to create an Amount

let moni = Amount 6.6 EUR

but i have no idea what to write to create an Account? (i hope that sentence makes sense) I don't know how to manipulate the input to do the whole add to account thing.

I've tried things like

let acc = Account 1 moni

My question is more how to manipulate the Account so I can write the function.

type creates a type synonym ; an Account is exactly the same as an (Integer, MoneyAmount) , and you write it the same way:

let acc = (1, moni)

A type is just an alias. It doesn't define a new type but instead a new name for an existing type. So you could do

type Money = Float

And you can use Money where ever you can use a Float and vice-versa. If you had

foo :: Float -> Float
foo x = 2 * x

Then

> foo (1 :: Float)
2
> foo (1 :: Money)
2

Both work fine. In your case, Account is just an alias for (Integer, MoneyAmount) , so you would construct one just as you would any other tuple.

A data defines an entirely new type, and this requires new constructors. For example:

data Bool = False | True

defines the Bool type with the constructors False and True . A more complicated example would be

data Maybe a = Nothing | Just a

which defines the Maybe a polymorphic type with constructors Nothing :: Maybe a and Just :: a -> Maybe a . I've included the types of these constructors to highlight that they exist as normal values and functions. The difference between a function and a constructor is that you can do anything you want in a function, but a constructor is only allowed to take existing values and make a value of another type without performing any transformations to it. Constructors are just wrappers around values.

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