在 Scala 3 中,我可以使用 lambda 类型为状态定义仿函数:
given stateFunctor[S]: Functor[[A] =>> State[S, A]] with
override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })
我希望它能与 ?
或 _
通配符一起使用:
given stateFunctor[S]: Functor[State[S, ?]] with
override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })
但我收到以下编译错误:
Type argument domain.State[S, ? <: AnyKind] does not have the same kind as its bound [_$1] given stateFunctor[S]: Functor[State[S, ? <: AnyKind]] with
为什么不起作用?我缺少什么?我认为 Scala 3 支持类型通配符的种类投影语法。
Scala 版本:3.1.3
如果您需要它,这里是State
和Functor
定义:
case class State[S, A](run:S => (S, A)):
def exec(s:S):S = run(s)._1
def eval(s:S):A = run(s)._2
trait Functor[F[_]]:
def map[A, B](a: F[A])(fx: A => B): F[B]
最佳答案
?
错误。 ?
用于存在类型 State[S, ?]
(在 Scala 2 中是 State[S, _]
又名 State[ S, A] forSome { type A }
),不适用于 lambda 类型。
_
代表 lambda 类型(在 Scala 2 中,它们被模拟 ({ type F[A] = State[S, A] })#F
)。所以它应该是 State[S, _]
但这尚未实现。
https://docs.scala-lang.org/scala3/reference/changed-features/wildcards.html
The syntax of wildcard arguments in types has changed from
_
to?
We would like to use the underscore syntax
_
to stand for an anonymous type parameter, aligning it with its meaning in value parameter lists. So, just asf(_)
is a shorthand for the lambdax => f(x)
, in the futureC[_]
will be a shorthand for the type lambda[X] =>> C[X]
.
到目前为止,您可以编写 [A] =>> State[S, A]
或使用 kind projector 状态[S,*]
scalaVersion := "3.2.1"
scalacOptions += "-Ykind-projector"
关于scala - 多态方法适用于 lambda 类型,但不适用于 Scala 3 中的类型通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74267610/