我看到至少两种不同的实现:
def add_streams(s1:Stream[Int], s2:Stream[Int]): Stream[Int] = Stream.cons(s1.head + s2.head, add_stream(s1.tail, s2.tail))
def add_streams(s1:Stream[Int], s2:Stream[Int]) =
(s1 zip s2) map {case (x,y) => x + y}
我猜最后一个更有效率,因为它不是递归的.
这是对的吗?你会如何编写这样的函数?