5. Custom Types

Created Saturday 23 August 2014

Overview

Type Synonyms

type String = [Char]
type Point = (Double,Double)

midpoint :: (Double,Double) -> (Double,Double)
-> (Double,Double)
midpoint (x1,y1) (x2,y2) =
((x1 + x2) / 2, (y1 + y2) / 2)
More clear way:
midpoint' :: Point -> Point -> Point
midpoint' (x1,y1) (x2,y2) =
((x1 + x2) / 2, (y1 + y2) / 2)

Newtype

newtype CustomerId = MakeCustomerId Int --'MakeCustomerId' — a constructor name
ERROR
badCustomer :: CustomerId
badCustomer = 13
FIXED
customer :: CustomerId
customer = MakeCustomerId 13
Extracting Int representation
customerToInt :: CustomerId -> Int
customerToInt (MakeCustomerId i) = i

Records

data Customer = Customer
{ name :: String }
data Supplier = Supplier
{ name :: String }
DEFINITION
data Customer = MakeCustomer
{ customerId :: CustomerId
, name :: String
, luckyNumber :: Int
}
INSTANTIATION
alice :: Customer
alice = MakeCustomer
{ customerId = MakeCustomerId 13
, name = "Alice"
, luckyNumber = 42
}
ACCESSING FIELDS
GHCi> customerId alice
Result: MakeCustomerId 13
GHCi> name alice
Result: "Alice"
GHCi> luckyNumber alice
Result: 42
UPDATING RECORDS WITH SOME NEW VALUES
sally = alice { name = "Sally", luckyNumber = 84 } --alice's records remain unchanged (pure functions..)

Algebraic Data Types

data Customer = MakeCustomer CustomerId String Int
OR
data Customer = Customer CustomerId String Int

alice :: Customer
alice = Customer (CustomerId 13) "Alice" 42

getCustomerId :: Customer -> CustomerId
getCustomerId (Customer cust_id name luckyNumber) =
cust_id
OR
getCustomerId :: Customer -> CustomerId
getCustomerId (Customer cust_id _ _) = cust_id

data RGB = RGB Double Double Double
x :: RGB

Tree

data StringTree = StringTree String [StringTree]
hierarchy = StringTree "C:"

[ StringTree "Program Files" []
, StringTree "Users"
[StringTree "Alice" []]
, StringTree "Cats" []
]

Algebraic Data Type Constructors

data Bool = False | True

x :: Bool
x = False
y :: Bool
y = True

negate :: Bool -> Bool
negate True = False
negate False = True

data DialogResponse = Yes | No | Help | Quit --enums in other languages

data MaybeInt = NoInt | JustInt Int --constructors can take values

defaultInt :: Int -> MaybeInt -> Int
defaultInt defaultValue NoInt = defaultValue
defaultInt _ (JustInt x) = x

data StringList = EmptyStringList
| ConsStringList String StringList
lengthStringList :: StringList -> Int
lengthStringList EmptyStringList = 0
lengthStringList (ConsStringList _ xs) =
1 + lengthStringList xs
IDENTICAL TO
length :: [a] -> Int
length [] = 0
length (_ : xs) = 1 + length xs

Parameterized Types

data Maybe a = Just a | Nothing
x :: Maybe Int
x = Nothing
fromMaybe :: a -> Maybe a -> a
fromMaybe defaultVal Nothing = defaultVal
fromMaybe _ (Just x) = x

data List a = Empty | Cons a (List a)

IMPLEMENTING DICTIONARY
data Map k a = ...



Backlinks: