무료 모나드를 이해하려고합니다. 그래서 자습서의 도움으로 나는 장난감 예제를 가지고 놀았지만 지금은 왜 컴파일되는지 이해하지 못합니다. 여기에 있습니다 :무료 모나드 해석기로이 코드를 컴파일하는 이유는 무엇입니까?
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)
}
}
나는 Interpreter의 적용 방법에 대해 이야기하고 있습니다. 그것은 Option [A]를 반환해야합니다,하지만 Option [Unit]과 Option [String]을 반환 할 수 있습니다. 그래서 컴파일 오류라고 가정합니다. 그러나 그렇지 않습니다. 이 코드는 컴파일되고 작동합니다 (비록 Idea가 오류라고 알려주지 만). 왜 그런가요?
UPD :하지만 왜 이렇게 컴파일되지 않습니까?
def test[A](o: Operation[A]): Option[A] = o match {
case Print(s) => Some(s)
case Read() => Some(Unit)
}
와우, scalac은 정말 똑똑합니다. 고맙습니다. –
이미 답변을 수락했으나 내 업데이트를 볼 수 있습니까? –
죄송합니다. 죄송합니다. 슬픈 것처럼 작동합니다. 업데이트를 삭제했습니다. –