问题描述
我有一个要排序的对象数组,其中排序谓词是异步的。 Scala是否具有用于基于类型签名为(T,T)->的谓词进行排序的标准或第三方库函数。 Future [Bool]
而不是(T,T)->布尔
?
I have an array of objects I want to sort, where the predicate for sorting is asynchronous. Does Scala have either a standard or 3rd party library function for sorting based on a predicate with type signature of (T, T) -> Future[Bool]
rather than just (T, T) -> Bool
?
或者,还有其他方法可以构造此代码吗?我已经考虑过找到列表元素的所有2对排列,在每个对上运行谓词并将结果存储在 Map((T,T),Bool)
中或具有某种效果的结构,然后对其进行排序-但我怀疑这样执行的比较将比幼稚的排序算法还要多。
Alternatively, is there some other way I could structure this code? I've considered finding all the 2-pair permutations of list elements, running the predicate over each pair and storing the result in a Map((T, T), Bool)
or some structure to that effect, and then sorting on it - but I suspect that will have many more comparisons executed than even a naive sorting algorithm would.
推荐答案
如果谓词是异步的,则您可能也希望获得异步结果,并避免使用 Await
If your predicate is async you may prefer to get an async result too and avoid blocking threads using Await
如果要根据将来的布尔谓词对 List [(T,T)]
进行排序,最容易对进行排序List [(T,T,Boolean)]
If you want to sort a List[(T,T)]
according to a future boolean predicate, the easiest it to sort a List[(T,T,Boolean)]
因此,给定一个 List [(T,T )]
和谓词(T,T)-> Future [Bool]
,如何获得 List [(T,T,Boolean)]
?或者,您想使用 Future [List [(T,T,Boolean)]]
来保持异步行为。
So given a you have a List[(T,T)]
and a predicate (T, T) -> Future[Bool]
, how can you get a List[(T,T,Boolean)]
? Or rather a Future[List[(T,T,Boolean)]]
as you want to keep the async behavior.
val list: List[(T,T)] = ...
val predicate = ...
val listOfFutures: List[Future[(T,T,Boolean]] = list.map { tuple2 =>
predicate(tuple2).map( bool => (tuple2._1, tuple2._2, bool)
}
val futureList: Future[List[(T,T,Boolean)]] = Future.sequence(listOfFutures)
val futureSortedResult: Future[List[(T,T)]] = futureList.map { list =>
list.sort(_._3).map(tuple3 => (tuple3._1,tuple3._2))
}
这是伪代码,我没有编译,也许没有,但是您明白了。
This is pseudo-code, I didn't compile it and it may not, but you get the idea.
密钥为 Future.sequence
,非常有用,可以将 Monad1 [Monad2 [X]]
转换为 Monad2 [Monad1 [X]]
,但请注意,如果将来的谓词失败,则全局排序操作也将失败。
The key is Future.sequence
, very useful, which somehow permits to transform Monad1[Monad2[X]]
to Monad2[Monad1[X]]
but notice that if any of your predicate future fail, the global sort operation will also be a failure.
如果您想下注在性能方面,将批处理返回到返回 Future [Boolean]
的服务调用可能是一个更好的解决方案。
例如,代替(T,T)-> Future [Bool]
也许您可以设计一个服务(如果您显然拥有它),例如 List [(T,T)]-> Future [List [(T,T,Bool)]
,这样您就可以在异步单次调用中获得所需的一切。
If you want better performance it may be a better solution to "batch" the call to the service returning the Future[Boolean]
.For example instead of (T, T) -> Future[Bool]
maybe you can design a service (if you own it obviously) like List[(T, T)] -> Future[List[(T,T,Bool)]
so that you can get everything you need in a async single call.
这篇关于Scala-根据Future结果谓词排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!