1

我一直在使用 Scala 中的 typeclass 模式以更好地理解它是如何工作的,因为我熟悉 Scalaz 并想弄清楚它是如何“在幕后”工作的。

(您可以使用https://ammonite.io/REPL运行以下代码)

import $plugin.$ivy.`org.spire-math::kind-projector:0.9.3`

sealed trait Maybe[+A] // Option
final case class Just[+A](value: A) extends Maybe[A]
final case object Null extends Maybe[Nothing]

sealed trait Direction[+E, +A] // Either
final case class Up[+E, +A](value: A) extends Direction[E, A]
final case class Down[+E, +A](value: E) extends Direction[E, A]

trait Functor[F[_]] {
  def map[A, B](fa: F[A])(f: A => B): F[B]
}

object FunctorSyntax {
  implicit final class FunctorExtensions[F[_], A](private val self: F[A]) extends AnyVal {
    def map[B](f: A => B)(implicit instance: Functor[F]): F[B] = {
      instance.map(self)(f)
    }
  }
}

object FunctorInstances {
  implicit val maybeFunctorInstance: Functor[Maybe] = new Functor[Maybe] {
    def map[A, B](fa: Maybe[A])(f: A => B): Maybe[B] = fa match {
      case Just(a) => Just(f(a))
      case n@Null => n
    }
  }

  implicit def directionFunctorInstance[E]: Functor[Direction[E, ?]] = new Functor[Direction[E, ?]] {
    def map[A, B](fa: Direction[E, A])(f: A => B): Direction[E, B] = fa match {
      case Up(a) => Up(f(a))
      case Down(e) => Down(e)
    }
  }
}

所以我写了一些Option( Maybe) 和Either( Direction) 的类似物,Functor定义,一些实例Functor,一些语法扩展,所以我可以调用.map有效的函子。

以下代码有效:

import FunctorInstances._
import FunctorSyntax._

val x: Maybe[Int] = Just(5)

println(x.map(_ + 1)) // prints "Just(6)"

正如预期的那样。但以下没有:

val y: Direction[String, Int] = Up(5)

println(y.map(_ + 1)) // errors out

抛出错误help.sc:48: value map is not a member of ammonite.$file.help.Direction[String,Int]

简而言之,我不希望发生此错误,并且不希望.map在任意Direction[E, ?].

我认为 Scala 无法看到Direction[String, Int]可以将其解构为F = Direction[String, ?]and A = String,从而阻止FunctorExtensions该类将自身包裹在val y: Direction[String, Int]. 不幸的是,我不知道如何解决这个问题。

注意:实例本身仍然可以通过implicitly

val instance = implicitly[Functor[Direction[String, ?]]]
println(instance.map(y)(_ + 1)) // prints "Up(6)"
4

2 回答 2

2

-Ypartial-unification如果您使用的是 Scala 2.11 或 Scala 2.12,则可能缺少scalac 选项。

添加scalacOptions += "-Ypartial-unification"到您的构建中,或者您可以使用默认启用的 Scala 2.13。

请参阅https://github.com/typelevel/cats/blob/v1.6.1/README.md#getting-started

于 2019-09-02T05:39:16.330 回答
1

这对我有用以下设置:

Welcome to the Ammonite Repl 1.6.3
(Scala 2.12.8 Java 1.8.0_141)

添加 interp 设置似乎有效

于 2019-09-02T06:28:32.060 回答