2

我一直在和 Scalaz 一起玩,以便在 scala 中获得一点haskell 的感觉。为了理解 scala 中的工作原理,我开始自己实现各种代数结构,并遇到了 Scalaz 人提到的一种行为。

这是我实现仿函数的示例代码:

trait Functor[M[_]] {
  def fmap[A, B](a: M[A], b: A => B): M[B]
}

sealed abstract class Foo[+A]
case class Bar[A]() extends Foo[A]
case class Baz[A]() extends Foo[A]

object Functor {

  implicit val optionFunctor: Functor[Option] = new Functor[Option]{
    def fmap[A, B](a: Option[A], b: A => B): Option[B] = a match {
      case Some(x) => Some(b(x))
      case None => None
    }   
  }

  implicit val fooFunctor: Functor[Foo] = new Functor[Foo] {
    def fmap[A, B](a: Foo[A], b: A => B): Foo[B] = a match {
      case Bar() => Bar()
      case Baz() => Baz()
    }   
  }
}

object Main {
  import Functor._

  def some[A](a: A): Option[A] = Some(a)
  def none[A]: Option[A] = None

    def fmap[M[_], A, B](a: M[A])(b: A => B)(implicit f: Functor[M]): M[B] =
      f.fmap(a, b)

  def main(args: Array[String]): Unit = { 
    println(fmap (some(1))(_ + 1)) 
    println(fmap (none)((_: Int) + 1)) 
    println(fmap (Bar(): Foo[Int])((_: Int) + 1))                                                    
  }
}

我为 Option 和一个虚假的 sumtype Foo 编写了一个仿函数实例。问题是 scala 无法在没有显式类型注释或包装方法的情况下推断隐式参数

def some[A](a: A): Option[A] = Some(a)

println(fmap (Bar(): Foo[Int])((_: Int) + 1))

Scala 在没有这些变通方法的情况下推断出 Functor[Bar] 和 Functor[Some] 之类的类型。

这是为什么?任何人都可以请我指出定义此行为的语言规范中的部分吗?

问候, raichoo

4

1 回答 1

6

您要求编译器执行两项任务:类型参数的本地类型推断(第 6.26.4 节)fmap和隐式搜索隐式参数(第 7.2 节)f。参考是Scala Reference

事情大致按以下顺序进行:

fmap[M = ?, A = ?, B = ?](Some(1))(x => x)

// type the arguments of the first parameter section. This is done
// without an expected type, as `M` and `A` are undetermined.
fmap[M = ?, A = ?, B = ?](Some(1): Some[Int])(x => x)(?) 

// local type inference determines `M` and `A`
fmap[Some, Int, B = ?](Some(1): Some[Int])(x => x)(?) 

// move to the second parameter section, type the argument with the expected type
// `Function1[Int, ?]`. The argument has the type `Function1[Int, Int]`
fmap[Some, Int, ?](Some(1): Some[Int])((x: Int) => x)                                                 

// local type inference determines that B = Int
fmap[Some, Int, Int](Some(1): Some[Int])((x: Int) => x)

// search local identifiers, and failing that the implicit scope of type `Functor[Some]]`, for an implicit
// value that conforms to `Functor[Some]`
fmap[Some, Int, Int](Some(1): Some[Int])((x: Int) => x)(implicitly[Functor[Some]])

隐式搜索Functor[Some]失败;Functor[Option]不符合。

于 2011-02-06T21:26:48.597 回答