Created
October 29, 2011 21:40
-
-
Save philipschwarz/1325125 to your computer and use it in GitHub Desktop.
Tail-recursive multiplyByTwo
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
public class Main | |
{ | |
public static void main(String[] args) | |
{ | |
List list = List.EMPTY_LIST; | |
int n = 6000; | |
while(n > 0) | |
list = list.cons(n--); | |
list = multiplyByTwo(list); | |
} | |
public static List multiplyByTwo(List list) | |
{ | |
return multiplyByTwo(list, List.EMPTY_LIST); | |
} | |
public static List multiplyByTwo(List list, List doubledList) | |
{ | |
if(list.isEmpty()) | |
{ | |
return doubledList.reverse(); | |
} | |
else | |
{ | |
return multiplyByTwo(list.tail(), doubledList.cons(2 * list.head())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment