0

Suppose there's a trait with abstract methods having different signatures (see below). To enable for-comprehension, I could define the same signature Result[A] for every abstract method.

However, to simplify trait's subclasses, I'd like to keep the simpler signatures for methods 2 and 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
 }

My question is how this could be done in Cats. (My attempts to lift takeStep to EitherT[Read, String, A] didn't succeed.) Or am I better off just defining the same Result[A] for each method?

schrödingcöder
  • 565
  • 1
  • 9
  • 18

1 Answers1

1

Try

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

or

def iteration(s: State, dir: Direction): Result[(Double, Gradient)] =  for{
  tee <- stepSize(s, dir)
  x   <- EitherT.right(takeStep(s, dir, tee))
} yield calculate(x)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • Thanks. The line `tee <- stepSize(s, dir)` gives me a type mismatch error: Found : `Double => EitherT[Read,Nothing,(Double, Gradient)]`. Required: `Double => EitherT[Read,String,(Double, Gradient)]` – schrödingcöder Oct 11 '18 at 20:08
  • I guess you didn't specify returning type of `iteration(..): Result[(Double, Gradient)]` as I did. So either specify the returning type or specify type parameter `String` here: `x <- EitherT.right[String](takeStep(s, dir, tee))`. – Dmytro Mitin Oct 11 '18 at 20:15