无法编译《猫的高级Scala》一书中的示例

时间:2019-03-21 09:48:06

标签: scala functional-programming scala-cats

我正在看书,并在那里玩例子。问题是我无法重现此示例:

  type Logged[A] = Writer[List[String], A]
  // Example method that returns nested monads:
  def parseNumber(str: String): Logged[Option[Int]] =
    util.Try(str.toInt).toOption match {
      case Some(num) => Writer(List(s"Read $str"), Some(num))
      case None => Writer(List(s"Failed on $str"), None)
    }

  // Example combining multiple calls to parseNumber:
  def addNumbers(
                  a: String,
                  b: String,
                  c: String
                ): Logged[Option[Int]] = {
    import cats.data.OptionT
    // Transform the incoming stacks to work on them:
    val result = for {
      a <- OptionT(parseNumber(a))
      b <- OptionT(parseNumber(b))
      c <- OptionT(parseNumber(c))
    } yield a + b + c
    // Return the untransformed monad stack:
    result.value
  }

编译错误:

Error:(30, 9) could not find implicit value for parameter F: cats.Monad[advancedScalaWithCats.monadTransformation.Part4UsagePatterns.Logged]
      b <- OptionT(parseNumber(b))
Error:(30, 9) not enough arguments for method flatMap: (implicit F: cats.Monad[advancedScalaWithCats.monadTransformation.Part4UsagePatterns.Logged])cats.data.OptionT[advancedScalaWithCats.monadTransformation.Part4UsagePatterns.Logged,Int].
Unspecified value parameter F.
      b <- OptionT(parseNumber(b))

1 个答案:

答案 0 :(得分:4)

添加

import cats.instances.list._