繁体   English   中英

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

[英]Lifting functions to monad transformers in 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]

尝试

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM