Last active
March 20, 2017 03:26
-
-
Save nafg/2a78a18771c2915ea7d07a1da4d31657 to your computer and use it in GitHub Desktop.
Mechanical steps to convert many algorithms written as a while loop to a tail-recursive function
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 fibImperative(index: Int): Int = { | |
var a = 0 | |
var b = 1 | |
var counter = 0 | |
while (counter < index) { | |
val c = a + b | |
a = b | |
b = c | |
counter = counter + 1 | |
} | |
a | |
} | |
/* | |
1. "Loop state" becomes function parameters | |
2. while condition becomes decision when to return | |
3. We loop by recursing | |
4. Reassignments become arguments passed in recursion | |
5. Resulting computation becomes what we return at the end | |
6. Initializers become arguments to first (outer) invocation | |
*/ | |
def fibRecursive(index: Int): Int = { | |
def loop(a: Int, b: Int, counter: Int): Int = { | |
if (counter < index) | |
loop(b, a + b, counter + 1) | |
else | |
a | |
} | |
loop(0, 1, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment