如何为 Monad Stack of State、Disjunction 和 List 定义函数? [英] How do I define a function for a Monad Stack of State, Disjunction, and List?

查看:74
本文介绍了如何为 Monad Stack of State、Disjunction 和 List 定义函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 monad List[Int].我想根据列表的值生成效果(分离和状态).这是我的 monad 堆栈和运行 monad 堆栈的代码.我的问题是定义 checkNum 的正确方法应该是什么,以便我可以生成正确的效果?

I've got a list monad List[Int]. I want to generate effects (Disjunction, and state) based on the values of the list. Here is my monad stack and the code to run the monad stack. My question is what should be proper way define checkNum so that I can generate the correct effects?

我的预期输出应该
List(("", \/-(1), ("Error: 2", -\/(Throwable())), ("",\/-(3)), ("Error: 4", -\/(Throwable())))

import scalaz._
import Scalaz._

type EitherTH[F[_], A] = EitherT[F, Throwable,A]
type StateTH[F[_], A] = StateT[F, String, A]
type StateTList[A] = StateTH[List, A]
type EitherTStateTList[A] = EitherTH[StateTList, A]
val lst = List(1,2,3,4)

def checkNum(x:Int)(implicit ms:MonadState[EitherTStateTList, Int]) = if ((x%2)==0) {
  put(s"Error: $x")
  -\/(new Throwable())
}  else {
   put("")
   \/-(x)
}  

val prg = for {
  x <- lst.liftM[StateTH].liftM[EitherTH]
  // y <- checkNum(x).liftM[EitherTH]
} yield y 

prg.run("")

推荐答案

在我看来 checkNum 应该返回一个 State[String, \/[Throwable,Int]]:

In my opinion checkNum should return a State[String, \/[Throwable,Int]]:

def checkNum0(x: Int): State[String, \/[Throwable,Int]] = if ((x%2)==0) {
  constantState(-\/(new Throwable()), s"Error: $x")
} else {
  constantState(\/-(x), "")
}

def checkNum1(x: Int): StateTList[\/[Throwable,Int]] = checkNum0(x).lift[List]

然后你可以把你的理解写成:

Then you can write your for-comprehension as:

val prg = for {
  x <- lst.liftM[StateTH].liftM[EitherTH]
  y <- EitherT(checkNum1(x))
} yield y

输出:

List(
  ("", \/-(1)),
  ("Error: 2", -\/(java.lang.Throwable)),
  ("", \/-(3)),
  ("Error: 4", -\/(java.lang.Throwable))
)

这篇关于如何为 Monad Stack of State、Disjunction 和 List 定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆