Scala IO monad: what's the point?

后端 未结 2 895
半阙折子戏
半阙折子戏 2021-02-01 05:14

I watched a video recently on how you could come up with the IO monad, the talk was in scala. I am actually wondering what the point of having functions return IO[A] out of them

2条回答
  •  暖寄归人
    2021-02-01 05:34

    The benefit of using the IO monad is having pure programs. You do not push the side-effects higher up the chain, but eliminate them. If you have an impure function like the following:

    def greet {
      println("What is your name?")
      val name = readLine
      println(s"Hello, $name!")
    }
    

    You can remove the side-effect by rewriting it to:

    def greet: IO[Unit] = for {
      _ <- putStrLn("What is your name?")
      name <- readLn
      _ <- putStrLn(s"Hello, $name!")
    } yield ()
    

    The second function is referentially transparent.

    A very good explanation why using the IO monads leads to pure programs can be found in Rúnar Bjarnason's slides from scala.io (video can be found here).

提交回复
热议问题