Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a List with values generated by function in Scala

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 _)
like image 900
Kiril Kirilov Avatar asked Aug 23 '11 15:08

Kiril Kirilov


People also ask

How do I create a list in Scala?

Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.

How do you create a uniform list in Scala?

fill() creates a list and fills it with zero or more copies of an element. This fills the list with seven instances of the integer 1. Hope this helps! If you need to know more about Scala, join Spark course today and become the expert.

How do I add values to a list in Scala?

This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.


1 Answers

How about this?

Stream.continually(generatorFunctionReturningInt()).take(max).sum
like image 100
Kim Stebel Avatar answered Oct 06 '22 00:10

Kim Stebel