Scala中高种类类型推断的限制是什么?

19
在下面的简化示例代码中:
case class One[A](a: A) // An identity functor
case class Twice[F[_], A](a: F[A], b: F[A]) // A functor transformer
type Twice1[F[_]] = ({type L[α] = Twice[F, α]}) // We'll use Twice1[F]#L when we'd like to write Twice[F]

trait Applicative[F[_]] // Members omitted
val applicativeOne: Applicative[One] = null // Implementation omitted
def applicativeTwice[F[_]](implicit inner: Applicative[F]): Applicative[({type L[α] = Twice[F, α]})#L] = null

我可以在applicativeOne上调用applicativeTwice,并且类型推断会生效,但是一旦我尝试在applicativeTwice(applicativeOne)上调用它,推断就失败了:

我可以在applicativeOne上调用applicativeTwice,并且类型推断会生效,但是一旦我尝试在applicativeTwice(applicativeOne)上调用它,推断就失败了:

val aOK = applicativeTwice(applicativeOne)
val bOK = applicativeTwice[Twice1[One]#L](applicativeTwice(applicativeOne))
val cFAILS = applicativeTwice(applicativeTwice(applicativeOne))

Scala 2.10.0中的错误包括:

- type mismatch; 
  found : tools.Two.Applicative[[α]tools.Two.Twice[tools.Two.One,α]]
  required: tools.Two.Applicative[F]
- no type parameters for method applicativeTwice: 
  (implicit inner: tools.Two.Applicative[F])tools.Two.Applicative[[α]tools.Two.Twice[F,α]]
  exist so that it can be applied to arguments 
  (tools.Two.Applicative[[α]tools.Two.Twice[tools.Two.One,α]]) 
  --- because --- 
  argument expression's type is not compatible with formal parameter type; 
     found : tools.Two.Applicative[[α]tools.Two.Twice[tools.Two.One,α]] 
     required: tools.Two.Applicative[?F]
为什么"?F"不能匹配任何东西(正确类型的)? 最终我想让applicativeTwice成为一个隐式函数,但我必须先让类型推断工作起来。 我看过类似的问题,并且答案指出了类型推断算法的限制。但是这种情况似乎相当有限制性,并且在单子变换器中一定很烦人,所以我怀疑自己错过了一些窍门来解决这个问题。

3
这可能也是一个相关的问题:是否有可能改善Scala中部分应用类型的类型推断? - EECOLOR
感谢这些有用的提示。结果发现2.10.1-RC3的行为也相同。 - Patrick Prémont
2个回答

28
你遇到了一个常见的问题:SI-2712。为了更加清晰,我会将你的代码简化一下:
import language.higherKinds

object Test {
  case class Base[A](a: A)
  case class Recursive[F[_], A](fa: F[A])

  def main(args: Array[String]): Unit = {
    val one = Base(1)
    val two = Recursive(one)
    val three = Recursive(two) // doesn't compile
    println(three)
  }
}

这个示例展示了与你遇到的相同类型的错误:

argument expression's type is not compatible with formal parameter type;
 found   : Test.Recursive[Test.Base,Int]
 required: ?F
        val three = Recursive(two) // doesn't compile
                    ^

首先,让我们了解一些您可能已经知道的语法和术语:

  • 在Scala中,我们说一个普通的、未参数化的数据类型(例如Int)具有_类型。它是单态的
  • Base,另一方面,是参数化的。如果不提供它包含的类型,我们不能将其用作值的类型,因此我们说它具有_[_]类型。它是rank-1多态:一个接受类型的类型构造函数。
  • Recursive更进一步:它有两个参数,F[_]A。这里的类型参数数量并不重要,但它们的种类很重要。F[_]是rank-1多态的,所以Recursiverank-2多态:它是一个接受类型构造函数的类型构造函数。
  • 我们称任何rank 2或以上的东西为higher-kinded,这就是乐趣开始的地方。

总体而言,Scala对于higher-kinded类型没有问题。这是区别于Java等语言的几个关键特性之一。但是,在处理higher-kinded类型时,它确实遇到了部分应用类型参数的问题。

问题在于:Recursive[F[_], A]有两个类型参数。在您的示例代码中,您使用了“类型lambda”技巧来部分应用第一个参数,类似于:

val one = Base(1)
val two = Recursive(one)
val three = {
  type λ[α] = Recursive[Base, α]
  Recursive(two : λ[Int])
}

这会让编译器确信你提供了与Recursive构造函数中的正确类型(_[_])相符的内容。如果Scala支持柯里化的类型参数列表,我肯定会在这里使用:

case class Base[A](a: A)
case class Recursive[F[_]][A](fa: F[A]) // curried!

def main(args: Array[String]): Unit = {
  val one = Base(1)          // Base[Int]
  val two = Recursive(one)   // Recursive[Base][Int]
  val three = Recursive(two) // Recursive[Recursive[Base]][Int]
  println(three)
}

遗憾的是,这个问题没有解决(见SI-4719)。所以,据我所知,处理这个问题最常见的方法是使用“unapply trick”,这是由Miles Sabin提出的。下面是scalaz中一个大大简化过的版本:

import language.higherKinds

trait Unapply[FA] {
  type F[_]
  type A
  def apply(fa: FA): F[A]
}

object Unapply {
  implicit def unapply[F0[_[_], _], G0[_], A0] = new Unapply[F0[G0, A0]] {
    type F[α] = F0[G0, α]
    type A = A0
    def apply(fa: F0[G0, A0]): F[A] = fa
  }
}

在有些模糊的术语中,这个Unapply结构就像是一个“一流类型lambda”。我们定义了一个trait来表示某种类型FA可以分解为类型构造器F[_]和类型A的断言。然后在其伴随对象中,我们可以定义隐式转换来提供各种类型的具体分解。我只在这里定义了我们需要使得Recursive适用的特定分解,但你也可以编写其他分解。
有了这个额外的管道,我们现在可以做我们需要的事情:
import language.higherKinds

object Test {
  case class Base[A](a: A)
  case class Recursive[F[_], A](fa: F[A])

  object Recursive {
    def apply[FA](fa: FA)(implicit u: Unapply[FA]) = new Recursive(u(fa))
  }

  def main(args: Array[String]): Unit = {
    val one = Base(1)
    val two = Recursive(one)
    val three = Recursive(two)
    println(three)
  }
}

Ta-da!现在类型推断已经可用,这段代码可以编译。作为练习,我建议您创建一个额外的类:
case class RecursiveFlipped[A, F[_]](fa: F[A])

......这与Recursive在任何实质性方面都没有区别,但会再次破坏类型推断。然后定义所需的额外管道以修复它。祝你好运!

编辑

您要求一个更加关注类型类的版本,需要进行一些修改,但希望您能看到相似之处。首先,这是我们升级后的Unapply

import language.higherKinds

trait Unapply[TC[_[_]], FA] {
  type F[_]
  type A
  def TC: TC[F]
  def apply(fa: FA): F[A]
}

object Unapply {
  implicit def unapply[TC[_[_]], F0[_[_], _], G0[_], A0](implicit TC0: TC[({ type λ[α] = F0[G0, α] })#λ]) =
    new Unapply[TC, F0[G0, A0]] {
      type F[α] = F0[G0, α]
      type A = A0
      def TC = TC0
      def apply(fa: F0[G0, A0]): F[A] = fa
    }
}

再次强调,这个方法完全借鉴自scalaz。下面是一些使用它的示例代码:

import language.{ implicitConversions, higherKinds }

object Test {

  // functor type class
  trait Functor[F[_]] {
    def map[A, B](fa: F[A])(f: A => B): F[B]
  }

  // functor extension methods
  object Functor {
    implicit class FunctorOps[F[_], A](fa: F[A])(implicit F: Functor[F]) {
      def map[B](f: A => B) = F.map(fa)(f)
    }
    implicit def unapply[FA](fa: FA)(implicit u: Unapply[Functor, FA]) =
      new FunctorOps(u(fa))(u.TC)
  }

  // identity functor
  case class Id[A](value: A)
  object Id {
    implicit val idFunctor = new Functor[Id] {
      def map[A, B](fa: Id[A])(f: A => B) = Id(f(fa.value))
    }
  }

  // pair functor
  case class Pair[F[_], A](lhs: F[A], rhs: F[A])
  object Pair {
    implicit def pairFunctor[F[_]](implicit F: Functor[F]) = new Functor[({ type λ[α] = Pair[F, α] })#λ] {
      def map[A, B](fa: Pair[F, A])(f: A => B) = Pair(F.map(fa.lhs)(f), F.map(fa.rhs)(f))
    }
  }

  def main(args: Array[String]): Unit = {
    import Functor._
    val one = Id(1)
    val two = Pair(one, one) map { _ + 1 }
    val three = Pair(two, two) map { _ + 1 }
    println(three)
  }
}

感谢您解释Unapply技巧。这是一种非常有趣的技术。不幸的是,经过几次尝试,我并没有看到它是否可以用于定义applicativeTwice或类似的东西。我想很可能Scalaz在某个地方包含了这样的内容。 - Patrick Prémont
@PatrickPrémont:我添加了一个更复杂的例子,希望能够解释一下你的 applicativeTwice 是如何工作的。这并不是唯一的方法;希望你可以从这里推断出更多。 - mergeconflict
1
感谢您提供更详细的解释!这似乎是一个实用的解决方法。 - Patrick Prémont

2

注意(三年后,2016年7月),scala v2.12.0-M5 开始实现 SI-2172(支持高阶单一化)。

请查看Miles Sabin的提交记录892a6d6

-Xexperimental 模式现在只包含 -Ypartial-unification

它遵循Paul Chiusano简单算法

// Treat the type constructor as curried and partially applied, we treat a prefix
// as constants and solve for the suffix. For the example in the ticket, unifying
// M[A] with Int => Int this unifies as,
//
//   M[t] = [t][Int => t]  --> abstract on the right to match the expected arity
//   A = Int               --> capture the remainder on the left

test/files/neg/t2712-1.scala包含以下内容:

package test

trait Two[A, B]

object Test {
  def foo[M[_], A](m: M[A]) = ()
  def test(ma: Two[Int, String]) = foo(ma) // should fail with -Ypartial-unification *disabled*
}

并且 (test/files/neg/t2712-2.scala):

package test

class X1
class X2
class X3

trait One[A]
trait Two[A, B]

class Foo extends Two[X1, X2] with One[X3]
object Test {
  def test1[M[_], A](x: M[A]): M[A] = x

  val foo = new Foo

  test1(foo): One[X3]     // fails with -Ypartial-unification enabled
  test1(foo): Two[X1, X2] // fails without -Ypartial-unification
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接