Trying a simple recursive function that takes a number, splits it in a certain way, and is only supposed to return it if the split numbers are equal to each other.
package main
import "fmt"
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
if y == x || sum > 200 {
return
} else {
split(sum+1)
return
}
}
func main() {
fmt.Println(split(10))
}
The output for fmt.Println(split(10))
is 4 and 6
, which is incorrect since they're not equal to each other. Is this due to the return statement t the end of my ELSE statement? I have a JAVA background so I figured that line would never get hit.
As you are declaring the variables in the function definition with (x, y int)
performing a return will return the values of x
and y
at that point. When you call the split function recursively it will assign a new x
and y
for that function call, so changing the values there will not effect the outer scope.
You can fix this by returning the return value of the recursive split
call, as currently you are ignoring the results by calling it on the line before the return.
However I would note that any input value > 0 will never be equal in this implementation and will return the same value for any input as the sum > 200
clause triggers.
https://play.golang.org/p/fzuPtqPCxpE
package main
import "fmt"
func split(sum int) (int, int) {
x := sum * 4 / 9
y := sum - x
if y == x || sum > 200 {
return
} else {
return split(sum + 1)
}
}
func main() {
fmt.Println(split(10))
}