Scala变量范围在对象中

时间:2012-06-21 21:47:38

标签: scala

我正在查看http://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/并且有一些代码我无法理解它是如何工作的:

object Functor {

  def fmap[A, B, F[_]](as: F[A])(f: A => B)(implicit functor: Functor[F]): F[B] =
    functor.fmap(as)(f)

  implicit object ListFunctor extends Functor[List] {
    def fmap[A, B](f: A => B): List[A] => List[B] =
      as => as map f
  }
}

具体来说,当ListFunctor.fmap的定义在as的范围内并且(据我所知){{{}}无法访问时,as如何访问Functor.fmap ListFunctor.fmap 1}}?

(与扭曲有关)上面的代码已经定义了以前的迭代:

trait Functor[F[_]] extends GenericFunctor[Function, Function, F] {
  final def fmap[A, B](as: F[A])(f: A => B): F[B] =
    fmap(f)(as)
}

object ListFunctor extends Functor[List] {
  def fmap[A, B](f: A => B): List[A] => List[B] = as => as map f
}

但同样,as似乎可以神奇地访问ListFunctor。我想如果我理解其中一个,我会理解另一个。

1 个答案:

答案 0 :(得分:3)

它与as不一样,只是在两个地方偶然使用相同的名称(可能不完全)。 as => as map f是一个函数定义,箭头前面的as是这个函数的参数声明。

如果写成x => x map f,那将完全等效。