Hello there here is my issue.
This is my running code, which is fine:
showBalls = do
howMany <- getInt
return . take HowMany $ repeat 9
where my getInt does several checks in order to retrieve user input Int. However, my question is, is there a way to rewrite this part of code with the use of monads?
My aim is to use >>= and have a final one-line functions such as:
showBalls = fmap (take <$> (repeat 9)) getLine
however it doesnt work (as expected).
Any suggestion?
You can use
flipto reverse the arguments oftake, which makes it possible to applyrepeat 9to it and get function:To use
>>=withgetIntwe needInt -> IO afunction:To get that, compose with
return(it’sm [a]because it will work for every monad, but is also restricted to lists; from the above type,mbecomesIOandbbecomes[a]):The final expression is:
But, as I mentioned, I’m not really convinced it’s strictly better than the original. As a more useful bit of knowledge, playing around with expressions and their types in GHCi is a good way of inventing transformations like that.