Created
February 18, 2016 02:27
-
-
Save ryandavidhartman/cc2b0ac71411c5be6ce8 to your computer and use it in GitHub Desktop.
Using the substitution model to visualize tail recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def factorial(n: Int) : Int = { | |
def factorialTR(acc: Int, n: Int) : Int = if (n == 1) acc else factorialTR(acc * n, n - 1) | |
factorialTR(1, n) | |
} | |
factorial(4) = | |
factorialTR(1, 4) = | |
if (4 == 1) 1 else factorialTR(1 * 4, 4 - 1) = | |
factorialTR(1 * 4, 4 - 1) = | |
factorialTR(4, 3) = | |
if (3 == 1) 4 else factorialTR(4 * 3, 3 - 1) = | |
factorialTR(4 * 3, 3 - 1) = | |
factorialTR(12, 2) = | |
if (2 == 1) 12 else factorialTR(12 * 2, 2 - 1) = | |
factorialTR(12 * 2, 2 - 1) = | |
factorialTR(24, 1) = | |
if (1 == 1) 24 else factorialTR(24 * 1, 1 - 1) = | |
24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment