How withFile is implemented in haskell

Following the 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 should we wrap resultin return? Does the specified function return a fvalue IO, as is evident by type Handle -> IO a?

+5
source share
2 answers

You are right: it falready returns IO, therefore, if the function was written as follows:

withFile' path mode f = do  
    handle <- openFile path mode   
    f handle

there would be no need for a refund. The problem is hClose handle, therefore, we must first save the result:

result <- f handle

and execution <-gets rid of IO. Therefore returnreturns it.

+7

, , Haskell. <- do-notation. result <- f handle " f handle result"; " result " " f handle" ( "" - , Monad, , IO ).

.. Monad <- m a a , , result <- f handle f result :: IO a, result :: a return result :: IO a.

PS- let ( in !), <-. :

withFile' :: FilePath -> IOMode -> (Handle -> IO a) -> IO a  
withFile' path mode f = do  
    handle <- openFile path mode   
    let result = f handle  
    hClose handle  
    result

, let , result IO a.

+3

All Articles