2

count takes Stream[Int] and desiredNum arguments. It adds the head of the stream (in a, I believe, lazy fashion) until the running sum >= the desiredNum.

Example: count(Stream.continually(1), 2) should get output of 2 since 1 + 1 = 2.

Here's my code:

  def count(as: Stream[Int], desiredNum: Int): Option[Int] = {
      def go(bs: Stream[Int], currentNum: Int, count: Int): Option[Int] = 
       bs match {
        case x #:: xs if(currentNum >= desiredNum) => Some(count)
        case x #:: xs => go(xs, currentNum + x, count + 1)
        case Stream() => None           
      }
      go(as, 0, 0)
   }

Tests:

scala> count(Stream(1), 1)
res0: Option[Int] = Some(1)

scala> count(Stream.continually(1), 100)
res0: Option[Int] = Some(100)

EDIT Note that I changed my question after seeing that I was not checking the right value in my first case statement. Initially I was using x (head of Stream) rather than currentNum. This led to an infinite loop.

But, is there a particular limit on desiredNum with respect to CPU and RAM? Is this function correctly using Stream's? (Perhaps there's a poor usage of RAM in count?)

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

1 Answers1

1

I believe your question reduces to "is count tail recursive". And it is. So no references to intermediate stream values (x) or computations (currentNum + 1) need be retained. Scala has the @tailrec annotation which lets the compiler verify that your recursion is in the tail position and thus is able to perform the tail call optimization.

Dustin Getz
  • 21,282
  • 15
  • 82
  • 131
  • Additionally, I was curious if my `count` function could be more concise. [I need to remember to use `@tailrec` - I usually forget] – Kevin Meredith Dec 23 '13 at 14:58