理解中的清单,未来和期权的组合-scalaz [英] Combining List, Future and Option in for-comprehension - scalaz

查看:91
本文介绍了理解中的清单,未来和期权的组合-scalaz的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:

val sth: Future[Seq[T, S]] = for {
  x <- whatever: Future[List[T]]
  y <- x: List[T]
  z <- f(y): Future[Option[S]]
  n <- z: Option[S]
} yield y: T -> n: S

我想使这段代码正常工作(我想每个人都可以理解这个想法,因为我添加了类型).

I would want to make this code to work(I guess everyone understands the idea as I've added types).

我的意思是说,工作"是指保持理解的结构并最终实现预期的类型.我知道有丑陋"的方式来做到这一点,但我想学习如何做到这一点:)

By "to work" I mean, that I would want to stay with the for-comprehension structure and fulfil expected types in the end. I know there are "ugly" ways to do it, but I want to learn how to do it pure :)

当我阅读互联网时,我得出的结论是,我的问题可以由monad变压器和放大器解决.斯卡拉兹.不幸的是,我找不到一个示例来帮助更好地理解我应该如何进行.

As I read the internet I've reached the conclusion that my problem may be solved by the monad transformers & scalaz. Unfortunately, I couldn't find an example to help understand better how should I proceed.

目前,我已经尝试过scalaz和Eff monad libs,但是我想我仍然不明白它是如何工作的,因为我无法解决自己的问题.

At the moment I've tried scalaz and Eff monad libs, but I guess I still don't understand how it works because I couldn't solve my problem.

我将不胜感激.

它应该是序列的未来,也考虑到我将其作为函数参数的无论是什么",对不起您的误导

It supposed to be future of sequence, also regarding the "whatever" I get it as a parameter of the function, sorry for misleading you

推荐答案

您可以使用scalaz

You could do something like what you need using the scalaz ListT monad transformer

 object Test {
   import scalaz._
   import ListT._
   type T = String
   type S = Int
   val whatever: Future[List[T]] = ??? // you get this somewhere
   def f(y: T): Future[Option[S]] = ??? // function that returns future of option

   val sth: Future[List[(T, S)]] = (for {
     y <- listT(whatever) 
     // you cannot mix list and option, but you can convert the option to a list of 1 item
     n <- listT(f(y).map(_.toList)) 
   } yield y -> n).run
 }

N.B .:由于您是从未来开始的,因此您无法返回Seq [(T,S)],只能拥有一个未来.如果要阻止并获取结果,则必须调用Await.result.

N.B.: Since you start with a future, you cannot return a Seq[(T,S)], you can only have a future. You have to call Await.result if you want to block and get the result.

这篇关于理解中的清单,未来和期权的组合-scalaz的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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