【问题标题】:Scala and cats: Implicit conversion to identity monadScala 和猫:隐式转换为身份单子
【发布时间】:2018-07-21 02:43:33
【问题描述】:

我有一个函数可以计算数值类型的平方和,如下所示。

import cats.syntax.functor._
import cats.syntax.applicative._
import cats.{Id, Monad}

import scala.language.higherKinds

object PowerOfMonads {
       /**
        * Ultimate sum of squares method
        *
        * @param x First value in context
        * @param y Second value in context
        * @tparam F Monadic context
        * @tparam T Type parameter in the Monad
        * @return Sum of squares of first and second values in the Monadic context
        */
    def sumOfSquares[F[_]: Monad, A, T >: A](x: F[A], y: F[A])(implicit num: Numeric[T]) : F[T] = {
        def square(value:T): T = num.times(value, value)
        def sum(first:T, second:T): T = num.plus(first, second)

        for {
            first <- x
            second <- y
        } yield sum(square(first), square(second))
    }
}

从客户端代码中,我想使用如下所示的函数

import cats.Id
import cats.instances.future._
import cats.instances.list._
import cats.instances.option._
import cats.syntax.applicative._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

println(s"Sum of squares for list ${PowerOfMonads.sumOfSquares(  List(1,2,3), List(1,2,3) )}")
println(s"Sum of squares for options ${PowerOfMonads.sumOfSquares(  Option(1), 2.pure[Option] )}")
println(s"Sum of squares for future ${PowerOfMonads.sumOfSquares(  1.pure[Future], Future(2) ).value}")
println(s"Sum of squares for id ${PowerOfMonads.sumOfSquares(1.pure[Id], 2.pure[Id])}")

现在,我想使用从数字类型 T 到 Id[T] 的隐式转换来调用函数 sumOfSquares,如下所示

println(s"Sum of squares for int ${PowerOfMonads.sumOfSquares(1, 2)}")

使用如下所示的函数

import cats.syntax.applicative._
import scala.language.implicitConversions
   /**
    * Implicit conversion for any numeric type T to Id[T]
    * @param value value with type T
    * @tparam T numeric type
    * @return numeric type wrapped in the context of an Identity Monad
    */
implicit def anyNum2Id[T](value:T)(implicit num: Numeric[T]):Id[T] = value.pure[Id]

但是,在执行程序时,出现以下错误

找不到类型的证据参数的隐式值 cat.Monad[[A]Any] println(s"int的平方和

${PowerOfMonads.sumOfSquares(1, 2)}") 方法的参数不足 sumOfSquares:(隐含证据$1:cats.Monad[[A]Any],隐含数量: 数字[T]) 任意。未指定值参数evidence$1, num. println(s"int ${PowerOfMonads.sumOfSquares(1, 2)}")

请帮我解决错误。

【问题讨论】:

  • 能否请您具体说明您正在使用的 scala 和 cats 版本?它似乎没有开箱即用,至少不是我的设置:PowerOfMonads给出“值flatMap不是类型参数F[A]的成员:first &lt;- x
  • 客户端代码的List 版本是否失败?对于Id 的情况,您是否尝试过在函数调用中指定类型参数?我从错误日志中看到的是解释器并没有猜测类型是Id,而是试图找到类型Any的Monad和Numberic的证据
  • @Andrey Tyukin:我使用的 Scala 版本是 2.12.4,cats 版本是 1.0.1。不要忘记编译器标志 scalacOptions += "-Ypartial-unification"
  • @Euge:客户端代码的列表版本有效。这个想法是不要让编译器推断不需要指定类型参数的类型。这里的问题是,编译器不会触发从“Int 到 Id”导入并带入作用域的隐式转换,而是直接尝试为任何类型的 Monad 和 Numeric 寻找证据。真正的问题是,是否有任何巧妙的技巧来帮助和指导编译器?我的目标是可行的还是超出了语言的范围?
  • 问题是,编译器无法猜测您特别想要从IntId 的转换。即使它是唯一的选择,它也必须搜索所有其他可能的选择,才能得出它实际上是唯一的结论。这超出了我所说的可计​​算性范围。

标签: scala monads implicit-conversion implicit scala-cats


【解决方案1】:

更改您的导入:

  import cats.syntax.flatMap._
  import cats.syntax.functor._
  import cats.Monad

  import scala.language.higherKinds

  object PowerOfMonads {
  ...

您可以帮助编译器推断类型:

PowerOfMonads.sumOfSquares(1: Id[Int], 2: Id[Int])

PowerOfMonads.sumOfSquares[Id, Int, Int](1, 2)

【讨论】:

  • 感谢您的建议,但我正在寻找一种不需要我显式指定类型但让编译器更努力地工作并通过隐式转换找到匹配的候选者的解决方案。在我的特殊情况下,应用从 Int 到 Id 的隐式转换,然后将它们应用为函数的参数。由于我的目标是获得客户端代码的优雅,因此如果无法应用隐式转换,重载函数定义也足够了。
  • 如果你不指定类型:PowerOfMonads.sumOfSquares(1, 2),编译器应该如何推断你的意思是PowerOfMonads.sumOfSquares[Id, Int, Int](1, 2),而不是例如PowerOfMonads.sumOfSquares[Const[Int]#λ, Int, Int](1, 2)type Const[C] = { type λ[T] = C }
  • @Dmytro Mitin:我不明白 Scala 怎么可能假设你想使用自定义类型:type Const[C] = { type λ[T] = C } 你给出的例子,当这种类型不和 Monads 有什么共同点吗?
  • @OctavianR。首先,没有任何共同点是不正确的。 Const[Int]#λcats.FlatMapId 也是。而MonadFlatMap 加上puresumOfSquares没有使用pure,所以可以用FlatMap来定义。如果我们不期望 FlatMap 的类型推断,我们为什么要为 Monad 做?其次,我们甚至可以为 Const[Int]#λ 定义一些 Monad 实例。这将是非法的,但为什么这应该是相关的?我希望我们不要指望 Scala 编译器检查 Monad 定律,对吗?是的,Const[Int]#λ 是自定义类型,Id 也是。
  • 我明白你的解释,但也许我遗漏了什么,因为我没有看到任何 Const 输入 cats.FlatMap link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 2012-04-15
相关资源
最近更新 更多