Scala:SeqT monad 转换器? [英] Scala: SeqT monad transformer?

查看:28
本文介绍了Scala:SeqT monad 转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有这样两个函数...

If we have such two functions...

def findUserById(id: Long): Future[Option[User]] = ???
def findAddressByUser(user: User): Future[Option[Address]] = ???

...然后我们可以使用cats OptionT monad 转换器来轻松地编写理解它们:

...then we are able to use cats OptionT monad transformer to write for-comprehension with them easily:

for {
  user    <- OptionT(findUserById(id))
  address <- OptionT(findAddressByUser(user))
} ...

我想以这种方式组合未来的序列,如下所示:

I'd like to compose future of sequences this way, like this:

def findUsersBySomeField(value: FieldValue): Future[Seq[User]] = ???
def findAddressesByUser(user: User): Future[Seq[Address]] = ???

for {
  user    <- SeqT(findUsersBySomeField(value))
  address <- SeqT(findAddressesByUser(user))
} ...

但我在 Cats 或 Scalaz 中找不到任何 SeqT 实现.是否存在这种 monad 转换器的某些实现,或者我需要自己编写 monad 转换器?不是太难,只是不想重新发明轮子.

But I can't find any SeqT implementation in Cats or Scalaz. Does some implementation of such monad transformer exist or I need to write monad transformer myself? Not that it too hard, just don't want to reinvent the wheel.

(我问题开头的示例来自 这篇文章)

(example at the beginning of my question is brought from this article)

推荐答案

Cats,从 1.0.0-MF 开始,什么都没有.这在他们的常见问题解答中有解释:

Cats, as of 1.0.0-MF have nothing of sorts. That is explained at their FAQ:

ListT 的简单实现存在关联性问题;请参阅此要点以获取示例.创建一个没有这些问题的 ListT 是可能的,但它往往效率很低.对于许多用例,嵌套可以用来达到预期的效果.

A naive implementation of ListT suffers from associativity issues; see this gist for an example. It's possible to create a ListT that doesn't have these issues, but it tends to be pretty inefficient. For many use-cases, Nested can be used to achieve the desired results.

Scalaz,从 7.2.15 开始有 StreamTListT,虽然后者 关联性问题.

Scalaz, as of 7.2.15 has StreamT and ListT, although the latter has associativity issues.

这篇关于Scala:SeqT monad 转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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