gpt4 book ai didi

scala - 类型构造函数推断的高阶统一

转载 作者:行者123 更新时间:2023-12-01 01:48:41 25 4
gpt4 key购买 nike

def meh[M[_], A](x: M[A]): M[A] = x
meh((x: Int) => "")

在 SI-2712 ( https://issues.scala-lang.org/browse/SI-2712 ) 修复之后,类型 A 被推断为最右边的类型参数。在我的 Function1[Int,String] 示例中,它是 String。

如何使它推断为左参数?

为什么这种方法不起作用?
class T[K,M]{}

def inferToLeft[S[_,_],K,B](ot: S[K,B]):({type Op[T] = S[T,B]})#Op[K]= ot

meh(inferToLeft(new T[Int,String]))

它仍然推断为 String 而不是 Int

最佳答案

编译器更喜欢尽快扩展没有稳定名称的类型(我不知道这样做的基本原理,抱歉),因此在调用 meh 之前简化了返回点的类型 lambda .好消息是你可以利用统一来概括它:

import scala.reflect.runtime._, universe._
import scala.language.higherKinds

def checkUnification[F[_], A: TypeTag](fa: => F[A]) = s"${typeOf[A]}"

implicit class InferToLeft[M[_, _], A, B](a: M[A, B]) {
def lefty: InferToLeft.U[M, B, A] = a
}

object InferToLeft {
type U[M[_, _], B, A] = M[A, B]
}

def e: Either[Int, String] = ???
def f: AnyRef => List[Int] = ???

assert(checkUnification(e) == "String")
assert(checkUnification(e.lefty) == "Int")
assert(checkUnification(f) == "scala.List[Int]")
assert(checkUnification(f.lefty) == "AnyRef")

这里的类型 InferToLeft.U在稳定路径上可用,因此您的参数作为 U[M, B, A] 传递不简化,统一挑 A ,这是类型构造函数的左参数。

关于scala - 类型构造函数推断的高阶统一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46263931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com