Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Haskell's Lazy and Strict monads (or transformers)

Tags:

When browsing Hackage, most of the monads have a Lazy and a Strict version. What is the difference exactly? Can you highlight it with some examples for the common monads (State, Reader, Writer)?

like image 775
ron Avatar asked Nov 01 '12 22:11

ron


People also ask

Is every monad Transformer a monad?

All monad transformers are instances of MonadTrans , and so lift is available for them all. There is a variant of lift specific to IO operations, called liftIO , which is the single method of the MonadIO class in Control.

What is the use of monads?

A monad is an algebraic structure in category theory, and in Haskell it is used to describe computations as sequences of steps, and to handle side effects such as state and IO. Monads are abstract, and they have many useful concrete instances. Monads provide a way to structure a program.

What is state monad?

The state monad is a built in monad in Haskell that allows for chaining of a state variable (which may be arbitrarily complex) through a series of function calls, to simulate stateful code.

Is list a monad Haskell?

Lists are a fundamental part of Haskell, and we've used them extensively before getting to this chapter. The novel insight is that the list type is a monad too! As monads, lists are used to model nondeterministic computations which may return an arbitrary number of results.


1 Answers

I don't know of a separation into lazy and strict for the reader monad, the reason for the State(T) and Writer(T) separation doesn't apply there.

The difference between the lazy and strict Writer and State monads resp. their monad transformers is the implementation of the monadic bind (>>=), fmap etc. In the strict versions, the implementation pattern-matches on the pair ((result, state), resp. (result, message)), forcing its evaluation (not the evaluation of its components), while the lazy versions use an irrefutable pattern ~(a,w) there, which does not force the evaluation of the pair.

The lazy versions allow some applications that are not possible for the strict versions, e.g.

foo = do     xs <- take 100 `fmap` sequence (repeat someAction)     doSomethingWith xs 

the sequence of an infinite list of actions can only start delivering its result if the (>>=) of the monad is sufficiently lazy.

On the other hand, using the lazy versions often leads to the build-up of large thunks in the (result, state) pairs, and thus to space and/or time leaks.

So both variants are offered, and you can choose which suits your needs better.

like image 104
Daniel Fischer Avatar answered May 29 '23 16:05

Daniel Fischer