25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Datatypes<br />

Constructors for datatypes come in two flavors: sum types and product types.<br />

A sum type consists of multiple options of type constructors under the same type. e two cases can be<br />

used at all locations the type is specified, and are discriminated using pattern matching.<br />

data Sum = A Int | B Bool<br />

A product type combines multiple typed fields into the same type.<br />

data Prod = Prod Int Bool<br />

Records are a special product type that, in addition to generating code for the constructors, generates a<br />

special set of functions known as selectors which extract the values of a specific field from the record.<br />

data Prod = Prod { a :: Int , b :: Bool }<br />

-- a :: Prod -> Int<br />

-- b :: Prod -> Bool<br />

Sums and products can be combined.<br />

data T1<br />

= A Int Int<br />

| B Bool Bool<br />

e fields of a datatype may be parameterized, in which case the type depends on the specific types the<br />

fields are instantiated with.<br />

data Maybe a = Nothing | Just a<br />

Values<br />

A list is a homogeneous, inductively defined sum type of linked cells parameterized over the type of its<br />

values.<br />

data List a = Nil | Cons a (List a)<br />

a = [1,2,3]<br />

a = Cons 1 (Cons 2 (Cons 3 Nil))<br />

List have special value-level syntax:<br />

15

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!