Scala和猫:隐式转换为身份monad

时间:2018-02-10 12:44:20

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

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

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]

但是,在执行程序时,我收到以下错误

  

无法找到类型的证据参数的隐含值   cats.Monad [[A] Any] println(s&#34; int的平方和

     

$ {PowerOfMonads.sumOfSquares(1,2)}&#34;)方法参数不够   sumOfSquares :(隐式证据$ 1:cats.Monad [[A] Any],隐式num:   数字[T])不限。未指定的值参数证明$ 1,num。     println(s&#34; int $ {PowerOfMonads.sumOfSquares(1,   2)}&#34)

请帮我解决错误。

1 个答案:

答案 0 :(得分: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)