Following a haskell tutorial, the author provides the following implementation of the withFile method:
withFile' :: FilePath -> IOMode -> (Handle -> IO a) -> IO a
withFile' path mode f = do
handle <- openFile path mode
result <- f handle
hClose handle
return result
But why do we need to wrap the result in a return? Doesn’t the supplied function f already return an IO as can be seen by it’s type Handle -> IO a?
You’re right:
falready returns anIO, so if the function were written like this:there would be no need for a return. The problem is
hClose handlecomes in between, so we have to store the result first:and doing
<-gets rid of theIO. Soreturnputs it back.