简体   繁体   English

在Java的流中,Haskell的scanl相当于什么?

[英]What is the equivalent of Haskell's scanl in Java's streams?

As this question asked for python, what is the equivalent of Haskell's scanl in Java's streams? 这个问题要求python时,在Java的流中Haskell的scanl相当于什么?

The best I've come up with so far is to use 到目前为止我提出的最好的是使用

reduce(identity, accumulator, combiner)

with an accumulator that keeps the latest result and accumulates the results in a list, though the combiner would presumably not be not used. 使用累加器保存最新结果并将结果累积到列表中,尽管可能不会使用组合器。 I'm also not sure how to prevent it from being used in parallel, where it would not work. 我也不确定如何防止它并行使用,它不起作用。

Perhaps Stream is the wrong interface for (an equivalent of) scanl? 也许Stream是(相当于)scanl的错误接口?

Looks like standard Stream API has no scanl equivalent. 看起来标准的Stream API没有scanl等价物。 One of the reasons is the fact that scanl is strictly left-to-right operation which makes it hard to have benefits from parallel processing (and parallel processing is an important part of Stream API). 其中一个原因是scanl是严格从左到右的操作,这使得很难从并行处理中获益(并行处理是Stream API的重要部分)。 You may however use third-party libraries like my free StreamEx library. 但是,您可以使用第三方库,例如我的免费StreamEx库。 It extends standard Stream API adding many more useful functions including the scanLeft : 它扩展了标准的Stream API,增加了许多有用的功能,包括scanLeft

List<Integer> list = IntStreamEx.range(10).boxed().scanLeft(Integer::sum);
System.out.println(list);
// outputs [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

This scanLeft operation is guaranteed to work even with parallel streams, but you're unlikely to have the speedup unless you have some computational intensive upstream operations which could be parallelized. 即使对于并行流,此scanLeft操作也可以保证工作,但除非您有一些可以并行化的计算密集型上游操作,否则您不太可能获得加速。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM