Scala: SeqT monad transformer?

佐手、 提交于 2021-02-08 04:47:34

问题


If we have such two functions...

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

...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))
} ...

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)


回答1:


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

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, as of 7.2.15 has StreamT and ListT, although the latter has associativity issues.



来源:https://stackoverflow.com/questions/45940139/scala-seqt-monad-transformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!