Scala猫中Monad变压器的提升功能

时间:2018-10-11 18:09:27

标签: scala functional-programming monads monad-transformers scala-cats

假设具有带有不同签名的抽象方法的特征(请参见下文)。为了理解,我可以为每个抽象方法定义相同的签名Result[A]

但是,为了简化trait的子类,我想保留方法2和3的简单签名。

import cats.data.{EitherT, Reader}
trait Domain{

   type  Read[A] = Reader[BoundsProblem, A]
   type Result[A] = EitherT[Read, String, A]

    def stepSize( s: State, direction: Direction): Result[Double] //depends on an injected context, can fail
    def takeStep( s: State, dir: Direction, stepSize: Double): Read[Variable] //depends on context, can't fail
    def calculate(x: Variable): (Double, Gradient) //context-independent, can't fail

     //doesn't compile: 
   def iteration(s: State, dir: Direction) =  for{
          tee <- stepSize(s, dir)
         x <- takeStep(s, dir, tee)
          r <- calculate(x)
      } yield  r
 }

我的问题是如何在Cats中完成此操作。 (我将takeStep提升为EitherT[Read, String, A]的尝试没有成功。)还是我最好为每种方法都定义相同的Result[A]

1 个答案:

答案 0 :(得分:1)

尝试

def iteration(s: State, dir: Direction): Result[(Double, Gradient)] =  for{
  tee <- stepSize(s, dir)
  x   <- EitherT.right(takeStep(s, dir, tee))
  r   = calculate(x)
} yield r

def iteration(s: State, dir: Direction): Result[(Double, Gradient)] =  for{
  tee <- stepSize(s, dir)
  x   <- EitherT.right(takeStep(s, dir, tee))
} yield calculate(x)