/* * Tail recursive and non-tail recursive * functions for computing sum of integers * Note that this is kind of silly as Go does not have * tail recursion optimization * @author gtowell * created: Aug 1, 2021 */ package main import "fmt" func main() { summ(10) summTR(10,0) } // not tail recursive version of sum func summ(mx int) int { if (mx<=0) { return 0; } return mx + summ(mx-1); } //tail recursive version of sum // this version is annoying because it requires the user to pass in tot func summTR(mx int, tot int) int { if mx <=0 { return tot } return summTR(mx-1, tot+mx) } // summTR2 does tail recursion, but uses a private recursive function to do so! // This gets past Go not alloing overloaded function names or default params!! func summTR2(mx int) int { var ttr func(int, int) int // need to define the variable first so it is available for the recursion ttr = func(mm int, tot int) int { if (mm<=0) { return tot } return ttr(mm-1, tot+mm) } return ttr(mx, 0) }