[Haskell-cafe] Feedback on use of State monad

Atrudyjane atrudyjane at protonmail.com
Thu Jul 13 21:29:44 UTC 2017

Hello Everyone,
In the HPFFP book, there's a homework problem where you're supposed to refactor a recursive function that rolls dice to return the number of rolls it takes to reach or exceed an input sum and the list of die that occurred. As practice, decided to take the solution and implement it using the State monad:
-- Refactor rollsCountLoggged to use State
-- limit sum count StdGen [Die]
type RollsState = (Int, Int, Int, StdGen, [Die])
-- count [Die]
type RollsValue = (Int, [Die])
runRolls :: State RollsState RollsValue
runRolls = do
(l, s, c, sg, xs) <- get
if (s >= l) then
return (c, reverse xs)
let (d, ng) = randomR (1, 6) sg
put (l, s + d, c + 1, ng, intToDie d : xs)
rollsCountState :: Int -> IO ()
rollsCountState n = print $ evalState (runRolls) (n, 0, 0, mkStdGen 0, [])
I'm wondering if that 'do' block under the else is a not so great stylistic choice. If the 'let' and 'put' is moved above the 'if', then that's just an unnecessary call at the end. Or is it just the nature of running inside a monad?
Thank You,

Sent with [ProtonMail](https://protonmail.com) Secure Email.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170713/ad680063/attachment.html>

More information about the Haskell-Cafe mailing list