fic*_*ion 7 scala list generator
我必须生成一些随机数并将它们相加.就像是
result = generateList(range(0, max), generatorFunctionReturningInt()).foreach(sum _)
Run Code Online (Sandbox Code Playgroud)
如果generateList生成一个Listsize = max和生成的值generatorFunctionReturningInt
或者可能是类似的东西
result = range(0, max).map(generatorFunctionReturningInt).foreach(sum _)
Run Code Online (Sandbox Code Playgroud)
Kim*_*bel 15
这个怎么样?
Stream.continually(generatorFunctionReturningInt()).take(max).sum
Run Code Online (Sandbox Code Playgroud)
Dav*_*low 11
各种集合类型的伴随对象具有一些方便的工厂方法.尝试:
Seq.fill(max)(generate)
Run Code Online (Sandbox Code Playgroud)
简单地
(0 to max).map(_ => (new util.Random).nextInt(max)).sum
Run Code Online (Sandbox Code Playgroud)
其中max定义数字数量和随机范围。
foreach旨在与副作用函数(如 println)一起使用的方法,该函数不返回任何内容 ( Unit)。