目的是使用Scala的Fibionacci创建Triangular number sequence
(1,3,6,10,15,21),并且需要返回第六位数。
测试
test("triangular") {
assert(Calculation.triangular(1, 3) === 21)
}
主要
def triangular(a: Int, b: Int) : Int = {
lazy val s: Stream[Int] = a #:: s.scanLeft(b)(_+_)
s(5)
}
结果
[info] - triangular *** FAILED ***
[info] 18 did not equal 21 (CalculationTest.scala:37)
[error] Failed: Total 9, Failed 1, Errors 0, Passed 8
[error] Failed tests:
[error] testingscala.CalculationTest
[error] (test:test) sbt.TestsFailedException: Tests unsuccessful
[error] Total time: 5 s, completed Jul 27, 2014 7:55:16 PM
scanLeft
将用于创建Fibionacci序列,但不能创建三角形序列。
需要使用哪个选项将2个,3个,4个,5个和随后的6个添加到最后一个数字,这将导致序列为1, 3, 6, 10, 15, 21
?
答案 0 :(得分:2)
像
这样的东西val triangular: Stream[Int] = Stream.from(2).scanLeft(1)(_+_)