简体   繁体   中英

Is there a way to "unwrap" IO monad in Haskell inside another io action?

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 ;
   

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM