问题
Hello i was wondering how can you unwrap a value at a later time in the IO monad?
If a<-expression
binds the result to a
then can't i use (<-expression)
as a parameter for a given method eg:
method (<-expression)
where method method
accepts the result of the evaluation?
Code
let inh=openFile "myfile" WriteMode
let outh=openFile "out.txt" WriteMode
hPutStrLn (<-outh) ((<-inh)>>=getLine)
I have not entered the Monad
chapter just basic <-
and do
blocks but i suppose it has to do with monads.
Then if i want to pass the result
if the evaluation to hGetLine
can't i use something like:
(<-expression)=>>hGetLine
回答1:
You already understand that <-
operator kind of unwraps IO
value, but it's actually the syntax of do
notation and can be expressed like this (actually I'm not sure, which results you're trying to achieve, but the following example just reads the content from one file and puts the content to another file):
import System.IO
main = do
inh <- openFile "myfile" ReadMode
outh <- openFile "out.txt" WriteMode
inContent <- hGetLine inh
hPutStrLn outh inContent
hClose outh
According to documentation hGetLine
, hPutStrlLn
and hClose
accept values of Handle
type as an argument, but openFile
returns IO Handle
, so we need to unwrap it using <-
operator
But if you want to use >>=
function instead, then this is one of the options of doing it:
import System.IO
writeContentOfMyFile :: Handle -> IO ()
writeContentOfMyFile handler =
openFile "myfile" ReadMode >>= hGetLine >>= hPutStrLn handler
main =
withFile "out.txt" WriteMode writeContentOfMyFile
来源:https://stackoverflow.com/questions/51491915/unwrap-value-from-io-operation-at-a-later-time