【问题标题】:What are the limitations on inference of higher-kinded types in Scala?Scala 中高级类型推理的限制是什么?
【发布时间】:2013-02-24 13:18:57
【问题描述】:

在下面的简化示例代码中:

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) 上调用它,推断就会失败:

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 成为一个隐式函数,但我必须首先让类型推断起作用。 我见过类似的问题,答案指出了类型推断算法的局限性。但是这种情况似乎非常有限,并且在 monad 转换器中一定很烦人,所以我怀疑我错过了一些解决这个问题的技巧。

【问题讨论】:

标签: scala type-inference higher-kinded-types unapply


【解决方案1】:

您遇到了一个常见的烦恼: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 多态的:它是一个接受类型构造函数的类型构造函数。
  • 我们称任何等级为 2 或以上的事物为 higher-kinded,这就是乐趣的开始。

Scala 通常不会遇到高级类型的问题。这是将其类型系统与 Java 等类型系统区分开来的几个关键特性之一。但是在处理更高种类的类型时,它确实有部分应用类型参数的问题。

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

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

这使编译器相信您正在为Recursive 构造函数提供正确类型的东西(_[_])。如果 Scala 有 curried 类型参数列表,我肯定会在这里使用它:

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)。因此,据我所知,处理此问题的最常见方法是 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 类型”。我们定义了一个特征,表示某个类型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)
  }
}

哒哒!现在类型推断有效,并且可以编译。作为练习,我建议您创建一个额外的类:

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
    }
}

再次,这是completely ripped off from 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很有可能在某个地方包含这样的东西。
  • @PatrickPrémont:我添加了一个更复杂的示例,我希望它可以解释这对您的applicativeTwice 是如何工作的。这不是唯一的方法。希望你能从这里推断出来。
  • 感谢您的详细解释!这似乎是一种实用的解决方法。
【解决方案2】:

注意(3 年后,2016 年 7 月),scala v2.12.0-M5 开始实现 SI-2172(支持更高阶的统一)

Miles Sabin看到commit 892a6d6

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

它遵循Paul Chiusanosimple algorithm

// 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
}

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2017-09-12
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多