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?
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.
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.
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.
The Maybe sum type is a useful data type that forms a functor. Like many other useful functors, it also forms a monad.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With