In what sense is the IO Monad pure?

后端 未结 9 1691
暗喜
暗喜 2020-12-04 08:41

I\'ve had the IO monad described to me as a State monad where the state is \"the real world\". The proponents of this approach to IO argue that this makes IO operations pure

9条回答
  •  星月不相逢
    2020-12-04 09:16

    Well, this is what we have been taught at college -

    Function is referentially transparent when it always returns the same value for specified input (or the same expression always evaluates to same value in the same context). Therefore, for example getChar would not be referentially transparent if it had type signature just () -> Char or Char, because you can get different results if you call this function multiple times with the same argument.

    But, if you introduce IO monad, then getChar can have type IO Char and this type has only one single value - IO Char. So getChar allways reutrns the same value, no matter on which key user really pressed.

    But you are still able to "get" the underlying value from this IO Char thing. Well, not really get, but pass to another function using bind operator (>>=), so you can work with the Char that user entered further in your program.

提交回复
热议问题