问题
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 aListT
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