Scala 中的函数函子
Function Functor in Scala
在学习 Scala 中的 Functor 的过程中,我遇到了 Function Functor,我有 2 个问题:
- Function1 的 Functor 类型参数中的这个签名是什么?
implicit def Function1Functor[R]: Functor[({type l[a]=(R) => a})#l] = new Functor[({type l[a]=(R) => a})#l] {
def fmap[A, B](r: R => A, f: A => B) = r andThen f
}
- 甚至没有编写 Function1Functor,我就能够从 sbt 控制台执行以下操作:
(x: Int) => x * 2 map (_ * 2)
这怎么可能?
见Weird nested structural type in generics
感觉奇怪:
scala> (x: Int) => x * 2 map (_ * 2)
<console>:11: error: value map is not a member of Int
(x: Int) => x * 2 map (_ * 2)
^
scala> { (x: Int) => x * 2 } map (_ * 2)
<console>:11: error: value map is not a member of Int => Int
{ (x: Int) => x * 2 } map (_ * 2)
如果后者适合您,也许您的 SBT 控制台会自动导入 Scalaz 功能;检查您的 build.sbt 是否有一行
initialCommands in console := "import scalaz._, Scalaz._"
顺便说一下,控制台应该会为您提供有关实际类型的提示
scala> {(x: Int) => x * 2} map (_ * 2)
res1: Int => Int = scalaz.std.FunctionInstances$$anon$$Lambda84/1646077266@29e39141
如果您想检查隐式解析过程,您可以切换以下选项,例如,在build.sbt中:
scalacOptions ++= Seq("-Xlog-implicits")
在学习 Scala 中的 Functor 的过程中,我遇到了 Function Functor,我有 2 个问题:
- Function1 的 Functor 类型参数中的这个签名是什么?
implicit def Function1Functor[R]: Functor[({type l[a]=(R) => a})#l] = new Functor[({type l[a]=(R) => a})#l] { def fmap[A, B](r: R => A, f: A => B) = r andThen f }
- 甚至没有编写 Function1Functor,我就能够从 sbt 控制台执行以下操作:
(x: Int) => x * 2 map (_ * 2)
这怎么可能?
见Weird nested structural type in generics
感觉奇怪:
scala> (x: Int) => x * 2 map (_ * 2) <console>:11: error: value map is not a member of Int (x: Int) => x * 2 map (_ * 2) ^ scala> { (x: Int) => x * 2 } map (_ * 2) <console>:11: error: value map is not a member of Int => Int { (x: Int) => x * 2 } map (_ * 2)
如果后者适合您,也许您的 SBT 控制台会自动导入 Scalaz 功能;检查您的 build.sbt 是否有一行
initialCommands in console := "import scalaz._, Scalaz._"
顺便说一下,控制台应该会为您提供有关实际类型的提示
scala> {(x: Int) => x * 2} map (_ * 2) res1: Int => Int = scalaz.std.FunctionInstances$$anon$$Lambda84/1646077266@29e39141
如果您想检查隐式解析过程,您可以切换以下选项,例如,在build.sbt中:
scalacOptions ++= Seq("-Xlog-implicits")