开发者

Generate a List with values generated by function in Scala

开发者 https://www.devze.com 2023-03-29 22:33 出处:网络
I must generate some random numbers and sum them. Something like result = generateList(range(0, max), generatorFunctionReturningInt()).foreach(sum _)

I must generate some random numbers and sum them. Something like

result = generateList(range(0, max), generatorFunctionReturningInt()).foreach(sum _)

If generateList开发者_如何学运维 generates a List with size = max and values generated by generatorFunctionReturningInt

Or may be something like

result = range(0, max).map(generatorFunctionReturningInt).foreach(sum _)


How about this?

Stream.continually(generatorFunctionReturningInt()).take(max).sum


The companion objects for various collection types have some handy factory methods. Try:

Seq.fill(max)(generate)


Simply

(0 to max).map(_ => (new util.Random).nextInt(max)).sum

where max defines both number of numbers and random range.

foreach method intended to be used with side-effect functions (like println) which returns nothing (Unit).


foreach is not for returning results, use map instead:

val result = Range (0, max).map (generatorFunctionReturningInt).map (sum _)

specifically, sum is already predefined, isn't it?

val result = Range (0, max).map (generatorFunctionReturningInt).sum

working code (we all like working code)

val result = Range (0, 15).map (3 + _).sum
result: Int = 150

For this trivial case it is the same as Range (3, 18).sum.

0

精彩评论

暂无评论...
验证码 换一张
取 消