我已经为使用免费monad的ETL过程实现了一种简单的语言。当使用List
作为数据读取和存储的输入和输出时,一切工作正常。不过我使用异步图书馆和Future[List]
如何在将来使用免费monad [M [_]]
常见的进口工作和定义
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import cats.free.Free
import cats.free.Free._
sealed trait Ops[A]
type OpsF[A] = Free[Ops, A]
与List
case class Fetch(offset: Int, amount: Int) extends Ops[List[Record]]
case class Store(recs: List[Record]) extends Ops[List[Response]]
def fetch(offset: Int, amount: Int): OpsF[List[Record]] =
liftF[Ops, List[Record]](Fetch(offset, amount))
def store(recs: List[Record]): OpsF[List[Response]] =
liftF[Ops, List[Response]](Store(recs))
def simpleEtl(offset: Int, amount: Int): Free[Ops, List[Response]] =
fetch(offset, amount).flatMap(r => store(r))
工作不Future[List]
case class Fetch(offset: Int, amount: Int) extends Ops[Future[List[Record]]]
case class Store(recs: List[Record]) extends Ops[Future[List[Response]]]
def fetch(offset: Int, amount: Int): OpsF[Future[List[Record]]] =
liftF[Ops, Future[List[Record]]](Fetch(offset, amount))
def store(recs: List[Record]): OpsF[Future[List[Response]]] =
liftF[Ops, Future[List[Response]]](Store(recs))
// explicit types in case I am misunderstanding more than I think
def simpleEtl(offset: Int, amount: Int): Free[Ops, Future[List[Response]]] =
fetch(offset, amount).flatMap { rf: Future[List[Record]] =>
val getResponses: OpsF[Future[List[Response]]] = rf map { r: List[Record] =>
store(r)
}
getResponses
}
工作如预期从...返回在flatMap
/map
是错误的 - 我没有得到OpsF[Future]
但Future[OpsF]
Error:(34, 60) type mismatch;
found : scala.concurrent.Future[OpsF[scala.concurrent.Future[List[Response]]]]
(which expands to) scala.concurrent.Future[cats.free.Free[Ops,scala.concurrent.Future[List[String]]]]
required: OpsF[scala.concurrent.Future[List[Response]]]
(which expands to) cats.free.Free[Ops,scala.concurrent.Future[List[String]]]
val getResponses: OpsF[Future[List[Response]]] = rf map { r: List[Record] =>
我目前的解决方法是让store
接受Future[List[Record]]
,并让翻译地图上的Future
,但感觉笨拙。
该问题不是特定于List
- Option
也会有用。
我做错了吗?这是否有某种单体变压器?
这似乎是一个monad变压器的典型模式,第一次看起来像是Haskell有一个'FreeT',但是无法在Scalaz或猫中找到它。 –
从[7.2.0]开始,scalaz拥有'FreeT'(https://oss.sonatype.org/service/local/repositories/archive/org/scalaz/scalaz_2.11/7.2.0/scalaz_2.11-7.2的3.0 javadoc.jar /!/ index.html的#scalaz.FreeT)。 –
我可以指向47度的图书馆吗?它恰当地命名为http://47deg.github.io/fetch/,它很快将成为一个类型级的孵化器?请注意,我没有为47度工作,但它似乎已经为您想要做的大部分工作提供了解决方案。 – wheaties