Scala类型检查器无法正确推断类型

我简化了一个与Scala类型推理有关的问题:

  case class HalfEdg[N,E](e:E, n:N)
  case class Nod[N,E](head:N, edgs:HalfEdg[N,E])

  case class AA[E](e:E) {
    def ->[N](n:N):HalfEdg[N,E] = HalfEdg(e,n)
  }
  def --[E](e:E):AA[E] = AA(e)

我可以做这个变量:

val x = Nod[Int,String](13, --("aa")->(12))

然后我想将它扩展到以下类型:

  case class Foo[N](e:N => Boolean)
  case class Bar[E](e:E => Boolean)

  case class BB[E](e:Bar[E]) {
    def ->[N](n:Foo[N]):HalfEdg[Foo[N],Bar[E]] = HalfEdg(e,n)
  }  
  def --?[E](e:E => Boolean):BB[E] = BB(Bar(e))

但是这次我不能做同样的事情,因为编译器无法推断出Foo和Bar内的函数类型:(我可以静态地输入它们并编译)

  val x1 = Nod[Foo[Int],Bar[String]](Foo(x => x == 10), --?(x => x == "")->(Foo(z => z == 10)))

我怎么解决这个问题?


类型推测失败围绕事实为中心,该编译器不能弄清楚该类型NFoo(z => z == 10)是相同的N作为类型N从早期Foo(x => x == 10) 。 一条可能的路线是确保FooBarBB--? 都使用相同的NE 这可以通过将它们包装在用类型NE参数化的父(“上下文”)特征中来完成。 例如:

trait Baz[N,E] {
  case class Foo(e:N => Boolean)
  case class Bar(e:E => Boolean)

  case class BB(e:Bar) {
    def ->(n:Foo):HalfEdg[Foo,Bar] = HalfEdg(e,n)
  }
  def --?(e:E => Boolean):BB = BB(Bar(e))
}

从这里开始,您可以在特定的上下文中执行所需的操作,作为Baz一个版本,满足NE所需的特定类型:

object IntStrBaz extends Baz[Int,String] {
  // do your work in here
  val x1 = Nod[Foo,Bar](Foo(x => x == 10), --?(x => x == "")->(Foo(z => z == 10)))
}

粘贴到REPL中,我们不再得到类型推断投诉:

scala> IntStrBaz.x1
res0: Nod[IntStrBaz.Foo,IntStrBaz.Bar] = Nod(Foo(<function1>),HalfEdg(Bar(<funct
ion1>),Foo(<function1>)))

所有你需要的是简化你的表情,它会很容易地显示你的错误。 您错过了两个设置类型的地方:

  val bbE = --?[String](x => x == "")
  val foo = Foo(z => z == 10)
  val zz = bbE->(foo)
  val x1 = Nod[Foo[Int],Bar[String]](Foo(x => x == 10), zz)

对于这样的问题,如果帮助编译器进行类型推断,则更容易识别问题。

链接地址: http://www.djcxy.com/p/38023.html

上一篇: Scala type checker cannot infer types correctly

下一篇: Inferred List Type with Either and Option