Scalaz `F[_] : Applicative` 类型约束如何暗示使用隐式参数?

发布于 2024-11-30 09:41:43 字数 1197 浏览 2 评论 0原文

我正在努力理解 Scalaz 中的遍历 特征:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

我不明白的部分是 F[_] : Applicative

现在,让我们看看 Applicative 是:

trait Applicative[Z[_]] extends Pointed[Z] with Apply[Z] {
  override def fmap[A, B](fa: Z[A], f: A => B): Z[B] = this(pure(f), fa)
  override def apply[A, B](f: Z[A => B], a: Z[A]): Z[B] = liftA2(f, a, (_:A => B)(_: A))
  def liftA2[A, B, C](a: Z[A], b: Z[B], f: (A, B) => C): Z[C] = apply(fmap(a, f.curried), b)
}

在这里,为了使 traverse 适用于某种类型 F,需要引入一个 Applicative[F 类型的隐式对象] 在范围内。

我想了解几件事:

  1. F[_] : Applicative 到底是什么意思?
  2. 为什么F[_]Applicative有关?我们需要Applicative[F],而不是F[something]扩展Applicative,对吧?
  3. 为什么此方法使用 Applicative[F] 类型的隐式值而不声明隐式参数?

I am struggling to understand the following function definition in Traverse trait in Scalaz:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

The part I don't understand is F[_] : Applicative.

Now, let's see what Applicative is:

trait Applicative[Z[_]] extends Pointed[Z] with Apply[Z] {
  override def fmap[A, B](fa: Z[A], f: A => B): Z[B] = this(pure(f), fa)
  override def apply[A, B](f: Z[A => B], a: Z[A]): Z[B] = liftA2(f, a, (_:A => B)(_: A))
  def liftA2[A, B, C](a: Z[A], b: Z[B], f: (A, B) => C): Z[C] = apply(fmap(a, f.curried), b)
}

Here, for traverse to work for some type F, one needs to bring an implicit object of type Applicative[F] in scope.

I'd like to understand several things:

  1. Wat exactly does F[_] : Applicative mean?
  2. Why does F[_] has something to do with Applicative? We need Applicative[F], not F[something] extends Applicative right?
  3. Why does this method use implicit values of type Applicative[F] without declaring implicit parameters?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话已封尘 2024-12-07 09:41:43

我认为所有三个问题都可以用以下表示法来回答:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

相当于:

def traverse[F[_], A, B](f: A => F[B], t: T[A])(implicit $ev: Applicative[F]): F[T[B]]

第一个表示法称为 F[_] 的上下文绑定

I think all three questions can be answered with the fact that this notation:

def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]]

is equivalent to this:

def traverse[F[_], A, B](f: A => F[B], t: T[A])(implicit $ev: Applicative[F]): F[T[B]]

The first notation is known as a context bound for F[_].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文