-1

I see this method:

trait Compressioner {
  def ioStream(is: InputStream, os: OutputStream, bufferSize: Int = 4096): Int = {
    val buffer = new Array[Byte](bufferSize)

      @tailrec
      def doStream(total: Int): Int = {
        val n = is.read(buffer)
        if (n == -1) total
        else {
          os.write(buffer, 0, n)
          doStream(total + n)
        }
      }

    doStream(0)
  }

So I just wanted to check to see if I understand this. We're initializing a Byte Array (and a byte is 8 bits long and is used to represent a character or letter) and that's our buffer (which is a temporary storage, often in memory).

What is the @ sign?

We then read from the input stream 4096 bytes a time (which is often 4096 characters at a time?). read returns -1 if there is nothing left and that's our end condition. Otherwise we take our bytes that we read and write it to the output stream. Is that correct interpretation of this? Did I say anything inaccurately?

Jwan622
  • 11,015
  • 21
  • 88
  • 181

1 Answers1

0

Actually tail recursion has nothing to do with Scala. It is the memory efficient recursion because what we do, while calculating the result we don’t keep the previous result in the recursion stack rather we keep the answer as the function parameter so while coming back from the recursion we don’t need the value we have calculated previously. It’s just a way to make your algorithm space efficient. Every recursive function can be written as a tail recursive function, how ever there is no mathematical proof for that!!!

You can refer to this link for more information about tail recursion. This is more of algorithmic explanation for tail recursion.

For example

Normal recursive function for factorial program.

def fact(n)={
If(n==0)
   return 1
  n*fact(n-1)
}

What will happen we will come down until n==0 Like this. fact(4)

4*fact(3)
3*fact(2)
2*fact(1)
1*fact(0) //it will return 1

But until we return 1 we need to have have all the other function call in memory to calculate the factorial eventually.

Tail recursive function

def factorial(n: Int): Int = {
  @tailrec
  def iter(x: Int, result: Int): Int =
if (x == 1) result
else iter(x - , result * x)

  iter(n, 1)
}


fact(5)

In tail recursive function the last call should be the function call that is the thing we should keep in mind.

https://www.google.co.in/amp/s/www.geeksforgeeks.org/tail-recursion/amp/

And particular to the Scala you can refer to this.

https://alvinalexander.com/scala/fp-book/tail-recursive-algorithms

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32