From Newsgroup: comp.lang.haskell
On 2019-08-06 14:54:01 +00, Thoai Nguyen wrote:
This is a fairly noob question. Considering the following imaginary functions:
someCalculation :: String -> Maybe String
someCalculation = Just
main :: IO ()
main = getLine >>= someCalculation >>= putStrLn
What I want to do is to run a non-deterministic calculation on an
input string, then print the output. In this case, 2 different monads
are in use (Maybe & IO). Of course this wouldn't work due to incorrect typing.
What would be the right way to handle something like this in Haskell?
The someCalculation implementation is just a placeholder, but you get the idea...
The first >>= needs to have the same type of Monad on each side of it,
which you are not doing. Also if you want to output the result though
putStrLn you need a function that converts you Maybe back to a String.
answerString :: Maybe String -> String
answerString = show
If you want to keep someCalculation free of the IO Monad you can nest
the Maybe inside the IO Monad:
getLine >>= return . someCalculation >>= putStrLn . answerString
or:
getLine >>= return . answerString . someCalculation >>= putStrLn
Note that any 'someCalculation >>= whatever' must return a Maybe, so you
can't go from 'Maybe a' to 'IO a' using just >>= operations.
--
Barry Fishman
--- Synchronet 3.21d-Linux NewsLink 1.2