Why is this code compiled with a free monad interpreter?

I'm trying to understand free monads. Therefore, with the help of textbooks, I wrote a toy example to play, and now I do not understand why it compiles. There he is:

import cats.free.Free
import cats.instances.all._
import cats.~>

trait Operation[+A]

case class Print(s: String) extends Operation[Unit]

case class Read() extends Operation[String]


object Console {

  def print(s: String): Free[Operation, Unit] = Free.liftF(Print(s))

  def read: Free[Operation, String] = Free.liftF(Read())

}

object Interpreter extends (Operation ~> Option) {
  // why does this compile?
  override def apply[A](fa: Operation[A]): Option[A] = fa match {
    case Print(s) => Some(println(s))
    case Read() => Some(readLine())
  }
}

object Main {
  def main(args: Array[String]) {
    val program = for {
      _ <- Console.print("What is your name?")
      name <- Console.read
      _ <- Console.print(s"Nice to meet you $name")
    } yield ()
    program.foldMap(Interpreter)
  }
}

I am talking about using the interpreter method. It should return Option [A], but I can return Option [Unit] and Option [String] here, so I assume that it should be a compilation error. But this is not so. This code compiles and works (although Idea tells me this is a bug). Why is this?

UPD: but why doesn't this compile?

def test[A](o: Operation[A]): Option[A] = o match {
    case Print(s) => Some(s)
    case Read() => Some(Unit)
  }
+4
source share
1 answer

, apply Option[A], A . , Operation[Unit], Option[Unit] ..

. , , Option[Unit] Option[A], , Print , , Operation[Unit]. - Option[Unit], Operation[Unit], . Read String. : Option[Unit] Read, , , .

, , ? , Scala ( IntelliJ) , . case Print , Operation[A] Operation[Unit], A = Unit .


:

case Print(s) => Some(s)

Operation[Unit] (, Print extends Operation[Unit]), Option[Unit], Some(s) Option[String]. .

case Read() => Some(Unit)

Unit - Unit, , Unit. Unit ().

, , : Operation[String], Operation[String], Operation[Unit] ( Operation[Unit.type]).

+3

Source: https://habr.com/ru/post/1661344/


All Articles