Is the monadic IO construct in Haskell just a convention?

后端 未结 4 1087
自闭症患者
自闭症患者 2021-01-30 20:46

Is the monadic IO construct in Haskell just a convention or is there is a implementation reason for it?

Could you not just FFI into libc.so instead to do your IO, and

4条回答
  •  爱一瞬间的悲伤
    2021-01-30 21:47

    Could you just FFI into libc.so instead to do IO and skip the IO Monad thing?

    Taking from https://en.wikibooks.org/wiki/Haskell/FFI#Impure_C_Functions, if you declare an FFI function as pure (so, with no reference to IO), then

    GHC sees no point in calculating twice the result of a pure function

    which means the the result of the function call is effectively cached. For example, a program where a foreign impure pseudo-random number generator is declared to return a CUInt

    {-# LANGUAGE ForeignFunctionInterface #-}
    
    import Foreign
    import Foreign.C.Types
    
    foreign import ccall unsafe "stdlib.h rand"
      c_rand :: CUInt
    
    main = putStrLn (show c_rand) >> putStrLn (show c_rand)
    

    returns the same thing every call, at least on my compiler/system:

    16807
    16807
    

    If we change the declaration to return a IO CUInt

    {-# LANGUAGE ForeignFunctionInterface #-}
    
    import Foreign
    import Foreign.C.Types
    
    foreign import ccall unsafe "stdlib.h rand"
      c_rand :: IO CUInt
    
    main = c_rand >>= putStrLn . show >> c_rand >>= putStrLn . show
    

    then this results in (probably) a different number returned each call, since the compiler knows it's impure:

    16807
    282475249
    

    So you're back to having to use IO for the calls to the standard libraries anyway.

提交回复
热议问题