我有一个最终的无标签 DSL 来构建简单的数学表达式:
trait Entity[F[_]] {
def empty: F[Int]
def int(value: Int): F[Int]
}
trait Operation[F[_]] {
def add(a: F[Int], b: F[Int]): F[Int]
}
我想实现一个 ZIO 解释器。根据module-pattern
指南,可能的实现如下所示:
type Entity = Has[Entity[UIO]]
object Entity {
val test: ULayer[Entity] =
ZLayer.succeed {
new Entity[UIO] {
override def empty: UIO[Int] =
ZIO.succeed(0)
override def int(value: Int): UIO[Int] =
ZIO.succeed(value)
}
}
def empty: URIO[Entity, Int] =
ZIO.accessM(_.get.empty)
def int(value: Int): URIO[Entity, Int] =
ZIO.accessM(_.get.int(value))
}
type Operation = Has[Operation[UIO]]
object Operation {
val test: ULayer[Operation] =
ZLayer.succeed {
new Operation[UIO] {
override def add(a: UIO[Int], b: UIO[Int]): UIO[Int] =
ZIO.tupled(a, b).map { case (x, y) => x + y }
}
}
def add(a: UIO[Int], b: UIO[Int]): URIO[Operation, Int] =
ZIO.accessM(_.get.add(a, b))
}
使用此实现构建表达式时,必须provideLayer
像这样重复调用:
Operation.subtract(
Entity.empty.provideLayer(Entity.test),
Entity.int(10).provideLayer(Entity.test)
).provideLayer(Operation.test)
这看起来更像是一种反模式。解释 DSL 的最惯用或最 ZIO 的方式是什么?