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.

data PlatonicSolid<br />

= Tetrahedron<br />

| Cube<br />

| Octahedron<br />

| Dodecahedron<br />

| Icosahedron<br />

deriving (Show, Eq, Ord, Read)<br />

example = show Icosahedron<br />

example = read ”Tetrahedron”<br />

example = Cube == Octahedron<br />

example = sort [Cube, Dodecahedron]<br />

IO<br />

A value of type IO a is a computation which, when performed, does some I/O before returning a value<br />

of type a. e notable feature of <strong>Haskell</strong> is that IO is still functionally pure; a value of type IO a is<br />

simply a value which stands for a computation which, when invoked, will perform IO. ere is no way<br />

to peek into its contents without running it.<br />

For instance, the following function does not print the numbers 1 to 5 to the screen. Instead, it builds<br />

a list of IO computations:<br />

fmap print [1..5] :: [IO ()]<br />

We can then manipulate them as an ordinary list of values:<br />

reverse (fmap print [1..5]) :: [IO ()]<br />

We can then build a composite computation of each of the IO actions in the list using sequence_,<br />

which will evaluate the actions from left to right. e resulting IO computation can be evaluated in<br />

main (or the GHCi repl, which effectively is embedded inside of IO).<br />

>> sequence_ (fmap print [1..5]) :: IO ()<br />

1<br />

2<br />

3<br />

4<br />

5<br />

>> sequence_ (reverse (fmap print [1..5])) :: IO ()<br />

5<br />

4<br />

3<br />

2<br />

1<br />

23

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

Saved successfully!

Ooh no, something went wrong!