Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a fold from within a for-comprehension?

I have the following snippet in Scala using Scalaz and Task/EitherT:

def myMethod(request: MyRequest) : EitherT[Task, Failure, Success] =
    EitherT[Task, Failure, Success](
      for {
        aamOpt <- async.findUser(request)
        aamEith <- Task.now(aamOpt.\/>(NoUserFound()))
        result <- aamEith.fold(err => Task.now(-\/(err)), aam => process(aam)).run)
      } yield result)

Where async.findUser returns a Task[Option[MyUser]] and process(aam) returns EitherT[Task, Failure, Success]. These return types are needed as these methods interact (down the line) with external services.

Is there any way to simplify the last line of the for comprehension into something nicer? I mean this one:

result <- aamEith.fold(err => Task.now(-\/(err)), aam => process(aam)).run)
like image 841
Pere Villega Avatar asked Dec 06 '25 06:12

Pere Villega


1 Answers

I would probably immediately lift the result from async.findUser into the relevant EitherT monad and then just flatMap:

def myMethod(request: MyRequest): EitherT[Task, Failure, Success] =
  EitherT.eitherT[Task, Failure, MyUser](
    async.findUser(request).map(_.\/>(NoUserFound()))
  ).flatMap(process)

This is untested but something like it should more or less work.

like image 126
Travis Brown Avatar answered Dec 08 '25 18:12

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!