Scala函数,用于计算包含算术序列的流

时间:2014-07-27 12:46:54

标签: scala

测试

test("arithmetic") {
  assert(Calculation.arithmetic(5, 10) === 30)
}

主要

def arithmetic(a: Int, b: Int) : Int = {
  val c = b - a
  val third = b + c
  val fourth = third + c
  val fifth = fourth + c
  fifth + c
}

在Scala中,可以使用val fibs = fibFrom(1, 1).take(7)创建a stream that contains a Fibonacci sequence。是否可以使用在Scala中创建Arithmetic序列的流?如果是积极的,如何实施呢?

1 个答案:

答案 0 :(得分:2)

斐波那契序列是一个算术序列,你可以创建你想要的任何序列:

scala> val s: Stream[Int] = 0 #:: s.map(_+5)
s: Stream[Int] = Stream(0, ?)

scala> s(10)
res0: Int = 50

scala> (s take 10).toList
res1: List[Int] = List(0, 5, 10, 15, 20, 25, 30, 35, 40, 45)