Recursive functions - helper method

Hello, i have been making the switch from JavaScript to Go and i am practicing some problem solving, trying to implement the “helper method”, but i am having some trouble. Can anyone give me a hand?


func main() {
	xs := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	fmt.Println(collectOddValues(xs))
}

func collectOddValues(arr []int) []int {
	result := []int{}
	var helper func([]int) []int

	helper = func(helperInput []int) []int {
		xs := helperInput
		if len(xs) == 0 {
			return []int{}
		}
		if helperInput[0]%2 != 0 {
			fmt.Println("Result:", result)
			return append(result, helperInput[0])
		}
		fmt.Println("xs:", xs)
		return helper(append(xs[:0], xs[1:]...))
	}
	fmt.Println("Result2:", result)
	return helper(arr)
}

Attached is the code:

NVM fixed it…

func main() {
	xs := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	fmt.Println(collectOddValues(xs))
}

func collectOddValues(xs []int) []int {
	//storage for odd values
	result := []int{}

	//declaring the helper function
	var helper func([]int) []int

	//defining the helper method function
	helper = func(helperInput []int) []int {

		//base case
		if len(helperInput) == 0 {
			//returning odd values when base case condition is met
			return result
		}
		//collecting odd values and storing inside of the result
		if helperInput[0]%2 != 0 {
			result = append(result, helperInput[0])
			fmt.Println("Result:", result)
		}

		//recursively deleting the first index in the slice
		return helper(append(helperInput[:0], helperInput[1:]...))
	}

	//beginning recursion
	return helper(xs)
}

If you are making the switch from js to go, you should leave the js idioms behind and embrace the Go approach. You don’t need callbacks and lambdas everywhere. You rarely need to define functions
that return other functions. Generally you just write simple code which does what you want.

If you find yourself defining lambdas anywhere, writing functions with more then 4 levels of indentation, or which are more than 100 lines long, then you are writing js, not Go.

1 Like