2

I see at least two different implementations:

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}

I guess the last one is more efficient since it is not recursive.
Is it correct? How would you code such a function ?

2 Answers 2

5

The first version is broken as it doesn‘t check for the end of a Stream. (The streams needn’t be of different length for this to happen.) Given that, the zip version is the one to prefer.

Sign up to request clarification or add additional context in comments.

Comments

2

First of all: your implementations have different behavior when either of the streams is finite. The first will crash with a NoSuchElementException, while the second will just truncate the longer stream.

I find the latter much more expressive and elegant, anyway, although I doubt the performance difference would be noticeable in most cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.