如何指定在具有独立类型参数的类匹配中引入的类型

时间:2019-10-25 06:16:38

标签: scala free-monad

我遵循了Runar Bjarnason关于免费单子的演讲:http://functionaltalks.org/2014/11/23/runar-oli-bjarnason-free-monad/

我从他的最初示例中得到了以下代码(我使用名称Continuation而不是Bind and Box而不是F-我现在更喜欢它们):

object TestFreeMonads
{
  sealed trait Interact[A]

  case class Ask(prompt: String) extends Interact[String]
  case class Tell(msg: String) extends Interact[Unit]


  sealed trait Free[Box[_], A] {
    def flatMap[B](f: A => Free[Box, B]): Free[Box, B] =
      this match {
        case Return(a) => f(a)
        case Continuation(v, cont ) => Continuation(v, cont andThen (_ flatMap f)   )
//      The following line does not compile: missing parameter type for expanded function ((<x$1: error>) => cont(x$1).flatMap(f))
//        case Continuation(v, cont ) => Continuation(v,  cont(_).flatMap(f) )
//      This line does compile:
//        case Continuation(v, cont ) => Continuation[Box, Any, B](v, cont(_).flatMap(f) )
      }

    def map[B](f: A => B): Free[Box, B] = flatMap(a => Return(f(a)))
  }

  case class Return[Box[_], A](a: A) extends Free[Box, A]
  case class Continuation[Box[_], I, A](v: Box[I], cont: I => Free[Box, A]) extends Free[Box, A]

  def lift[Box[_], A](v: Box[A]): Free[Box, A] = Continuation(v, (a: A) => Return(a))

  implicit def liftInteract[A](v: Interact[A]) : Free[Interact, A] = lift(v)

  def prog: Free[Interact, Unit]  = {
    for {
      first <- Ask("First Name")
      last <- Ask("Last Name")
      _ <- Tell(s"Hello, $first $last")
    } yield ()
  }

}

我不明白为什么这行会编译:{{1​​}},而不是为什么这一行:case Continuation(v, cont ) => Continuation(v, cont andThen (_ flatMap f) )

第三行case Continuation(v, cont ) => Continuation(v, cont(_).flatMap(f) )也可以编译,但是它很冗长,我使用Any作为I类型参数的值,我认为这是有问题的。理想情况下,我应该以某种方式声明v的类型并使用它,但这似乎是不可能的。

最终v的类型为I,但是有点儿不懂。

我使用了scala 2.13.1:

case Continuation(v, cont ) => Continuation[Box, Any, B](v, cont(_).flatMap(f) )

1 个答案:

答案 0 :(得分:4)

尝试绑定类型变量i(小写)

case Continuation(v, cont: Function1[i, _]) => Continuation(v, cont(_: i).flatMap(f))

您还可以使用文字模式

case c: Continuation[Box, i, A] => Continuation(c.v, c.cont(_: i).flatMap(f))