理解中的清单,未来和期权的组合

编程入门 行业动态 更新时间:2024-10-25 02:27:40
本文介绍了理解中的清单,未来和期权的组合-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 ListT monad转换器

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.

更多推荐

理解中的清单,未来和期权的组合

本文发布于:2023-11-29 23:00:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647887.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   期权   清单   未来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!