Create a list with the values ​​generated by the function in Scala

I have to generate some random numbers and sum them up. Sort of

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

If generateList creates a List with size = max and the values ​​generated by generatorFunctionReturningInt

Or maybe something like

 result = range(0, max).map(generatorFunctionReturningInt).foreach(sum _) 
+6
source share
4 answers

Simply

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

where max determines both the number of numbers and the random range.

foreach to be used with side effect functions (e.g. println) that returns nothing ( Unit ).

+4
source

How about this?

 Stream.continually(generatorFunctionReturningInt()).take(max).sum 
+14
source

Companion objects for various types of collections have several convenient factory methods. Try:

 Seq.fill(max)(generate) 
+9
source

foreach is not for returning results, use a map instead:

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

in particular, the amount is already predetermined, right?

 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, this is the same as Range (3, 18).sum .

0
source

Source: https://habr.com/ru/post/895689/


All Articles