我在学习如何使用FreeMonads来为我的服务实现解释器。我如何链接行为并与Scalaz一起解释它们?
假设我有
sealed trait ServiceAction[T] extends Product with Serializable
case class ConsumeCommand(cmd: AccruePoints) extends ServiceAction[AccruePointModel]
case class CreateEvent(evt: PointsAccruedEvent) extends ServiceAction[PointsAccruedEvent]
sealed trait LogAction[T] extends Product with Serializable
case class Info(msg: String) extends LogAction[Unit]
case class Error(msg: String) extends LogAction[Unit]
和行动
type LogActionF[A] = Free[LogAction, A]
type ServiceActionF[A] = Free[ServiceAction, A]
下的单子,我这样定义我的服务:
trait PointAccrualService {
def consume(cmd: AccruePoints): ServiceActionF[AccruePointModel] = Free.liftF(ConsumeCommand(cmd))
def emit(evt: PointsAccruedEvent) : ServiceActionF[PointsAccruedEvent] = Free.liftF(CreateEvent(evt))
}
和
trait LogService {
def info(msg: String) : LogActionF[Unit] = Free.liftF(Info(msg))
def error(msg: String) : LogActionF[Unit] = Free.liftF(Error(msg))
}
与每个
object LogService extends LogService
object PointAccrualService extends PointAccrualService
我LogServiceInterpreter
对象是这样的:
case class LogServiceConsoleInterpreter() extends LogServiceInterpreter {
def apply[A](action: LogActionF[A]): Task[A] = action.foldMap(handler)
protected def handler = new (LogAction ~> Task) {
override def apply[A](fa: LogAction[A]) = fa match {
case Info(m) =>
now(info(m))
case Error(m) =>
now(error(m))
}
}
def info(msg: String): Unit = {
println(s"INFO: $msg")
}
def error(msg: String): Unit = {
println(s"ERROR: $msg")
}
}
同样,我PointAccuralServiceInterpreter
是这样的:
case class PointAccuralServiceInterpreter() {
def apply[A] (action: ServiceActionF[A]) : Task[A] = action.foldMap(handler)
protected def handler = new (ServiceAction ~> Task) {
override def apply[A](fa: ServiceAction[A]): Task[A] = fa match {
case ConsumeCommand(cmd) => {
println("Service ConsumeCommand:" + cmd)
now(cmd)
}
case CreateEvent(evt) => {
println("Service CreateEvent:" + evt)
now(evt)
}
}
}
}
我的逻辑很简单,我想记录,并消耗我的命令,然后创建一个事件,有点像事件源:
val ret = for {
_ <- logService.info("Command: " + cmd)
model <- service.consume(cmd)
_ <- logService.info("Model: " + model)
evt <- service.emit(model.toEvent("200", "Event Sent"))
_ <- logService.info("Event:" + evt)
} yield evt
此代码甚至没有实际编译。
我应该从这里做什么?我认为我应该使用Coproduct来链接它们并通过提供我的解释器来执行这段逻辑。
我发现这里的东西 https://groups.google.com/forum/#!topic/scalaz/sHxFsFpE86c
,或者它说我可以用无形这样做 Folding a list of different types using Shapeless in Scala
他们都太复杂了。我想要的是,在定义我的逻辑之后,我该如何执行它?
希望我在这里提供足够的细节以获得答案。我真的很想学这个。谢谢
你的问题是不明确的。 – pedrofurla
对不起,让我添加更多的代码。我赶紧和其他人一起吃午饭。我应该把更多的东西放在身体里 – sowen