Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeated calling a Haskell monad

I have a Haskell function that returns a monad, declared as follows:

data Options = Options {
    optGames :: Int,
    optSuits :: Int,
    optVerbose :: Bool
  } deriving Show

playGame :: Options -> StateT StdGen (WriterT [String] IO)) Bool

This function plays a single game of solitaire, then returns a boolean indicating a win or loss, along with a log in the WriterT monad.

I would like to call this function a set number of times, each time using the "next" value of the random generator (StdGen), and concatenating the Bool return values into a list.

I tried creating a recursive function to do the calls, but can't figure out how to pass the monad into each next iteration.

I would like to emulate

initial state >>= playGame >>= playGame ... -- repeat N times

and collect all of the resulting Bool values, as well as the log entries from the WriterT monad.

What is the best way to do this?

like image 673
Ralph Avatar asked Jun 08 '12 20:06

Ralph


People also ask

What does monad mean in Haskell?

What is a Monad? 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.

How do you make a monad in Haskell?

To create a monad, it is not enough just to declare a Haskell instance of the Monad class with the correct type signatures. To be a proper monad, the return and >>= functions must work together according to three laws: (return x) >>= f ==== f x.

What problem do monads solve?

Monad is a simple and powerful design pattern for function composition that helps us to solve very common IT problems such as input/output, exception handling, parsing, concurrency and other. Application becomes less error prone.

Is maybe a monad?

The Maybe sum type is a useful data type that forms a functor. Like many other useful functors, it also forms a monad.


1 Answers

I think you're looking for replicateM. This repeats the given action a specified number of times, returning the result as a list. So replicateM n playGame corresponds to playing the game n times and getting a list of the results back.

like image 153
Tikhon Jelvis Avatar answered Sep 27 '22 19:09

Tikhon Jelvis