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.

e IO monad is wired into the runtime with compiler support. It is a special case and most monads in<br />

<strong>Haskell</strong> have nothing to do with effects in this sense.<br />

putStrLn :: String -> IO ()<br />

print :: Show a => a -> IO ()<br />

e type of main is always IO ().<br />

main :: IO ()<br />

main = do<br />

putStrLn ”Enter a number greater than 3: ”<br />

x 3)<br />

e essence of monadic IO in <strong>Haskell</strong> is that effects are reified as first class values in the language and reflected<br />

in the type system. is is one of foundational ideas of <strong>Haskell</strong>, although it is not unique to <strong>Haskell</strong>.<br />

Monad Transformers<br />

Monads can be combined together to form composite monads. Each of the composite monads consists<br />

of layers of different monad functionality. For example, we can combine an error-reporting monad with<br />

a state monad to encapsulate a certain set of computations that need both functionalities. e use of<br />

monad transformers, while not always necessary, is often one of the primary ways to structure modern<br />

<strong>Haskell</strong> programs.<br />

class MonadTrans t where<br />

lift :: Monad m => m a -> t m a<br />

e implementation of monad transformers is comprised of two different complementary libraries,<br />

transformers and mtl. e transformers library provides the monad transformer layers and mtl<br />

extends this functionality to allow implicit lifting between several layers.<br />

To use transformers, we simply import the Trans variants of each of the layers we want to compose and<br />

then wrap them in a newtype.<br />

{-# LANGUAGE GeneralizedNewtypeDeriving #-}<br />

import Control.Monad.Trans<br />

import Control.Monad.Trans.State<br />

import Control.Monad.Trans.<strong>Write</strong>r<br />

newtype Stack a = Stack { unStack :: StateT Int (<strong>Write</strong>rT [Int] IO) a }<br />

deriving (Monad)<br />

24

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

Saved successfully!

Ooh no, something went wrong!