Skip to content

Instantly share code, notes, and snippets.

@philipschwarz
Created October 29, 2011 21:40
Show Gist options
  • Save philipschwarz/1325125 to your computer and use it in GitHub Desktop.
Save philipschwarz/1325125 to your computer and use it in GitHub Desktop.
Tail-recursive multiplyByTwo
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