Sequencing both Scalaz WriterT and Either with for-yield

后端 未结 1 1761
孤街浪徒
孤街浪徒 2021-02-10 18:16

If I have:

import scala.concurrent._
import scalaz._, Scalaz._

type Z = List[String]
type F[α] = Future[α]
type WT[α] = WriterT[F, Z, α]

implicit val z: Monoid         


        
1条回答
  •  [愿得一人]
    2021-02-10 19:06

    you should wrap your Future monad in the EitherT, sightly modifying your code. It would look like that:

    type EFT[α] = EitherT[F, Throwable, α]
    type WEFT[α] = WriterT[EFT, Z, α]
    
    def bazA(): WEFT[Int] = WriterT.put[EFT, Z, Int](EitherT.right[F, Throwable, Int](f.point(18)))(z.zero)
    
    def bar(): WEFT[Int] = for {
      a <- bazA
      b <- bazA
    } yield a + b
    

    You can also define lift functions (which lifts the value from one monad to your transformer) to avoid boilerplate.

    def liftW[A](fa: Future[A]): WLET[A] = {
        WriterT.put[MLT, Z, A](EitherT.right[Future, Throwable, A](fa))(z.zero)
     }
    
      def bbar(): WLET[Int] = for {
        a ← liftW(6.point[F])
        b ← liftW(6.point[F])
      } yield a + b
    

    I am sure that lift functions are present in scalaZ, but I am always struggling to find them, and it appears that sometimes these are easier to write yourself.

    0 讨论(0)
提交回复
热议问题