Describe a computation

zer*_*ing 2 functional-programming scala io-monad

I have the following code, that I would like to know, why the variable number gets evaluated twice:

import cats.effect.IO

import scala.util.Random

object Main {

  private val number: IO[Int] =
    IO(Random.between(3, 300))

  def main(args: Array[String]): Unit = {


    number
      .flatMap { e =>
        println(e);
        number
      }.flatMap { e =>
      println(e);
      IO.unit
    }.unsafeRunSync()
  }

}
Run Code Online (Sandbox Code Playgroud)

the program prints two different numbers, although the number is an assignment. I know here, I describe a computation not a execution, and at the end of the universe, I run the program.

The question is, why it prints out two different numbers?

Mic*_*ann 5

There is a difference between

private val number: IO[Int] = IO(Random.nextInt())
Run Code Online (Sandbox Code Playgroud)

and

private val number2: Int = Random.nextInt()
Run Code Online (Sandbox Code Playgroud)

number is a value that when evaluated computes a random number. When evaluated multiple times this value of type IO (aka this computation) is run multiple times resulting in multiple different random numbers.

Whereas number2 when evaluated is just a single number.

It is very similar to the distinction between a lambda (val lambda = () => Random.nextInt()) and a value (val value = Random.nextInt()).

  • 让我们使用* evaluation *来将表达式替换为其值。让我们使用* computation *作为`IO`类型的值的通用名称,例如* strings *是`String`类型的值。 (2认同)