In particular I want to use pure Haskell functions on the results on console input. I'm curious if exists something like ?
operator from rust.
this snippet complains that words expect the type String, while its supplied wrapped into an io action. But i can't even use >>=
operator since as far as i understand i cannot instantiate IO constructor directly. So, does it mean all the standard library functions can't work with io even in the scope of io action?
thing :: IO ()
thing = do
let mbwords = words $ getLine ;
CodePudding user response:
Since Haskell is not designed to be totally useless, there must be a way. And there is more than one indeed.
What you looking for is something like this
main = do
line <- getLine
let mbwords = words line
or perhaps
main = do
mbwords <- fmap words getLine
Note you use <-
to "open" the monadic value inside the do-block, not let
.
Also note instantiating IO constructors is not necessary as long as you have functions that return IO actions, such as print
. You can express the same idea with
main = fmap words getLine >>= print
(of course you can use an arbitrary action of the right type instead of print
).