是什么 ?类型? [英] What is the ? type?

查看:47
本文介绍了是什么 ?类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为具有多个类型参数的类型实现一个cats Monad 实例.我查看了cats Either 实例,看看它是如何在那里完成的.下面复制了来自猫的 Either Monad 实例代码的一部分:

I am trying to implement a cats Monad instance for a type that has multiple type parameters. I looked at the cats Either instance to see how it was done there. Part of the Either Monad instance code from cats is copied below:

import cats.Monad

object EitherMonad {
  implicit def instance[A]: Monad[Either[A, ?]] =
    new Monad[Either[A, ?]] {
      def pure[B](b: B): Either[A, B] = Right(b)

      def flatMap[B, C](fa: Either[A, B])(f: B => Either[A, C]): Either[A, C] =
        fa.right.flatMap(f)
    }
}

编译失败,报错:error: not found: type ?

什么是 ? 类型?在为自己的类型创建实例时如何使用它?

What is the ? type and how can I use it when creating instances for my own types?

推荐答案

它是由 善良的投影仪插件.

Either[A, ?]

({type L[X] = Either[A, X]})#L

整个代码脱糖

import cats.Monad

object EitherMonad {
  implicit def instance[A]: Monad[({type L[X] = Either[A, X]})#L] = new Monad[({type L[X] = Either[A, X]})#L] {
    def pure[B](b: B): Either[A, B] = Right(b)

    def flatMap[B, C](fa: Either[A, B])(f: B => Either[A, C]): Either[A, C] =
      fa.right.flatMap(f)
  }
}

类型 lambda 看起来很可怕,但它们本质上是一个非常简单的概念.你有一个需要两个类型参数的东西,比如 Either[A, B].你想为Either 提供一个monad 实例,但是trait Monad[F[_]] 只接受一个类型参数.但原则上没问题,因为你的 monad 实例只关心第二个(正确的")类型参数.类型 lambda 只是修复"第一个类型参数的一种方式,以便您拥有正确的形状.

Type lambdas look frightening, but they are essentially a very simple concept. You have a thing that takes two type parameters, like Either[A, B]. You want to provide a monad instance for Either, but trait Monad[F[_]] takes only one type parameter. But in principle that's OK, since your monad instance is only concerned with the second (the "right") type argument anyway. A type lambda is just a way to "fix" the first type argument so you have the right shape.

如果你在价值层面做同样的事情,你甚至不会再三考虑.你得到了一个有两个参数的函数

If you would do the same thing at value level, you wouldn't even think about it twice. You got a function of two arguments

val f: (Int, Int) => Int = ...

你想传递 f 的东西,它只需要 1 个参数

And something you want to pass f to, which only takes 1 argument

def foo(x: Int => Int) = ...

使事情合适的唯一方法是修正其中一个论点

The only way to make things fit is to fix one of the arguments

foo(x => f(1, x))

这正是类型 lambda 在类型级别所做的.

And that's exactly what a type lambda does at type level.

这篇关于是什么 ?类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆