25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

(:) = Cons<br />

[] = Nil<br />

(1 : (2 : (3 : []))) = [1,2,3]<br />

A tuple is a heterogeneous product type parameterized over the types of its two values.<br />

Tuples also have special value-level syntax.<br />

data Pair a b = Pair a b<br />

a = (1,2)<br />

a = Pair 1 2<br />

(,) = Pair<br />

Tuples are allowed (with compiler support) to have up to 15 fields in GHC.<br />

Pattern matching<br />

Pattern matching allows us to discriminate on the constructors of a datatype, mapping separate cases to<br />

separate code paths.<br />

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

maybe :: b -> (a -> b) -> Maybe a -> b<br />

maybe n f Nothing = n<br />

maybe n f (Just a) = f a<br />

Top-level pattern matches can always be written identically as case statements.<br />

maybe :: b -> (a -> b) -> Maybe a -> b<br />

maybe n f x = case x of<br />

Nothing -> n<br />

Just a -> f a<br />

Wildcards can be placed for patterns where the resulting value is not used.<br />

const :: a -> b -> a<br />

const x _ = x<br />

List and tuples have special pattern syntax.<br />

16

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

Saved successfully!

Ooh no, something went wrong!