Parameterized Types
java has ArrayList<Int>
Haskell has parameterized types.
The Maybe Type:
data Maybe a = Nothing | Just a
Maybe is a container type that can hold 0 or more items of type a. There could be 0 items in the container, but things in the container are of type a.
A general List type:
data List a
= Empty
| Cons a (List a)
#more
Lists are built right into haskell. The ‘type’ of a list that stores a's is [a].
[1,2,3]
1:2:3:[]
1:(2:(3:[]))
-- all do the same thing
--map for 'normal lists'
map :: (a -> b) -> [a] -> [b]
map f = go
where
go [] = []
go (x:xs) = f x : go xs
Records
product types so far:
data Point2D = P Double Double
data StudentRecord = SR Int String String Transcript
--record syntax:
data Point2D =
P {x, y :: Double}
p = P 3 4
q = P {x=3,y-4} --args can be in any order
‘updating’ records:
--take this object, build a new record with the same vibe but change a few fields.
data Point = P {x, y :: Double} deriving Show
p = P 3 4
q = p {y = 5.0}
--q now has x=3.0 y = 5.0
Newtype
semantically no different from ‘data’, but drastically diff in runtime costs
allowed to use newtype IF AND ONLY IF
-the type must have exactly one data constructor
-the data constructor must take exactly one argument
under the hood, you can represent a newtype bannernumber exactly as an int. it doesnt store any extra data.
for other data types, they need to store a tag to indicate which constructor it uses, as well as the other data in the type.
newtype BannerNumber = B Int
newtype BannerNumber = B int deriving (Eq, Ord)
--record syntax
newtype BannerNumber = B {asInt :: Int}
newtype Cont r a = Cont {runCont :: ((a -> r) -> r) } --continuation monad
Why use a newtype if it just gets treated as whatever is in it?
because operations on newtype might be different. EX: can add integers, but cant add banner numbers.
newtype is not an instance of Num, or Eq, or whatever, that defines what functions can be used on the type.
*Builds better abstractions, helps compiler catch logic errors.
can give it these functionalities explicitly with ‘deriving’
Type Aliases:
in c: typedef (char *) string;
--in haskell:
type String = [Char] --official definition
type Cont r a = ContT r Identity a
--type aliases name the same tpye:
Index