Scala-REPL和编译中使用(Cats)Functor的不同行为

时间:2018-03-27 17:02:52

标签: scala-cats

import cats.{Functor, Monoid}

trait Fold[I, O] {
  type M

  def m: Monoid[M]

  def tally: I => M

  def summarize: M => O
}

object Fold {
  def apply[I, O, _M](_m: Monoid[_M])(_tally: I => _M, _summarize: _M => O): Fold[I, O] = new Fold[I, O] {
    override type M = _M

    override def m = _m

    override def tally = _tally

    override def summarize = _summarize
  }
}

object BeautifulFold  extends App {
  def fold[I, O](input: Seq[I])(f: Fold[I, O]): O =
    f.summarize(input.foldLeft(f.m.empty)((x, y) => f.m.combine(x, f.tally(y))))

  def sum[M](implicit ev: Monoid[M]): Fold[M, M] = Fold.apply(ev)(identity, identity)

  implicit def foldFunctor[I] = new Functor[({type F[X] = Fold[I, X]})#F] {
    override def map[A, B](fa: Fold[I, A])(f: A => B): Fold[I, B] =
      Fold(fa.m)(fa.tally, fa.summarize.andThen(f))
  }

  import cats.implicits._

  fold(List(1,2,3))(sum)

  fold(List(1,2,3))((sum[Int]:Fold[Int,Int]).map(s => s"Sum is $s"))
}

在REPL :paste模式下完美运行,但它会抛出错误,

[error] value map is not a member of Fold[Int,Int]
[error]   fold(List(1,2,3))((sum[Int]:Fold[Int,Int]).map(s => s"Sum is $s"))

sbt compile期间。 SBT版本为1.1.0

build.sbt的部分设置为,

scalaVersion := "2.12.4"
val catsVer = "1.1.0"

scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature", "-Xlog-implicits", "-Ypartial-unification")

libraryDependencies in ThisBuild ++= Seq(
  "org.typelevel" %% "cats-core" % catsVer,
  "org.typelevel" %% "cats-macros" % catsVer,
  "org.typelevel" %% "cats-kernel" % catsVer,
  "org.typelevel" %% "cats-free" % catsVer,
  ...

我的编辑设置有什么问题?感谢。

更新1

此代码段没有任何问题。我做错了是我在实际项目中没有像-Ypartial-unification那样包含scalacOptions。还有另一件事,请参考答案。

1 个答案:

答案 0 :(得分:1)

如{C} README文件中所述,将-Ypartial-unification选项包含到scalacOptions非常重要。如果您有一个多模块项目,如何完成它也很重要。该选项应添加到需要此选项的模块中。如果最好是全局选项,请将其放在公共设置列表中,如,

lazy val commonSettings = Seq(
  organization := "org.teckhooi",
  version := "1.0-SNAPSHOT",
  publishArtifact in (Compile, packageDoc) := false,
  publishArtifact in packageDoc := false,
  sources in(Compile, doc) := Seq.empty,
  logLevel := util.Level.Info,
  scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature", "-Xlog-implicits", "-Ypartial-unification")
)

lazy val root = project aggregate(foo, bar)

lazy val foo = project.settings(commonSettings)

lazy val bar = project.settings(commonSettings)