为什么方法参数 F 可以和类型构造函数 F 同名?
Why can method parameter F have the same name as type constructor F?
我在看 John De Goes "FP to the Max" 的视频。在代码中,他做了类似这样的事情来获取隐式对象:
object Program {
def apply[F[_]](implicit F: Program[F]): Program[F] = F
}
这是否意味着变量名 F(implicit F: Program[F]
中的第一个)实际上是不同的 F
?这是非常混乱的。他的意思是:
object Program {
def apply[F[_]](implicit ev: Program[F]): Program[F] = ev
}
编译如何在返回 F
时知道他指的是哪个 F
?范围内的类型构造函数或变量?
确实函数参数T
不同于类型参数T
,例如
def f[T](T: T): T = T
f(42) // res0: Int = 42
编译器不会混淆,因为 values 存在于 from types:
...there exist two separate universes, the universe of types and the
universe of values. In the universe of values, we have methods which
take values as arguments in round parentheses (or occasionally curly
braces). In the universe of types, we have type constructors, which take types
as arguments in square brackets.
处理类型类时有时会使用此约定。它旨在传达我们想要简单地 return 为 F
解析的类型类实例。为避免混淆,您可以使用您已经在问题中建议的 ev
方法,甚至
object Program {
def apply[F[_]: Program]: Program[F] = implicitly[Program[F]]
}
作为旁注,在类型类的伴生对象中使用 apply
方法的技巧使我们能够避免必须使用 implicitly
,例如,给定
trait Foo[T]
trait Bar[T]
trait Program[F[_]]
implicit val fooProgram: Program[Foo] = ???
implicit val barProgram: Program[Bar] = ???
object Program {
def apply[F[_]: Program]: Program[F] = implicitly
}
然后我们可以写
Program[Bar]
而不是
implicitly[Program[Bar]]
How does the compile know which F
he is referring to while returning the F
? The type constructor or the variable in scope?
编译器知道一个method/function只能return一个值。那么 =
有 类型但 不是 类型。
我在看 John De Goes "FP to the Max" 的视频。在代码中,他做了类似这样的事情来获取隐式对象:
object Program {
def apply[F[_]](implicit F: Program[F]): Program[F] = F
}
这是否意味着变量名 F(implicit F: Program[F]
中的第一个)实际上是不同的 F
?这是非常混乱的。他的意思是:
object Program {
def apply[F[_]](implicit ev: Program[F]): Program[F] = ev
}
编译如何在返回 F
时知道他指的是哪个 F
?范围内的类型构造函数或变量?
确实函数参数T
不同于类型参数T
,例如
def f[T](T: T): T = T
f(42) // res0: Int = 42
编译器不会混淆,因为 values 存在于
...there exist two separate universes, the universe of types and the universe of values. In the universe of values, we have methods which take values as arguments in round parentheses (or occasionally curly braces). In the universe of types, we have type constructors, which take types as arguments in square brackets.
处理类型类时有时会使用此约定。它旨在传达我们想要简单地 return 为 F
解析的类型类实例。为避免混淆,您可以使用您已经在问题中建议的 ev
方法,甚至
object Program {
def apply[F[_]: Program]: Program[F] = implicitly[Program[F]]
}
作为旁注,在类型类的伴生对象中使用 apply
方法的技巧使我们能够避免必须使用 implicitly
,例如,给定
trait Foo[T]
trait Bar[T]
trait Program[F[_]]
implicit val fooProgram: Program[Foo] = ???
implicit val barProgram: Program[Bar] = ???
object Program {
def apply[F[_]: Program]: Program[F] = implicitly
}
然后我们可以写
Program[Bar]
而不是
implicitly[Program[Bar]]
How does the compile know which
F
he is referring to while returning theF
? The type constructor or the variable in scope?
编译器知道一个method/function只能return一个值。那么 =
有 类型但 不是 类型。