The other day, I was solving a leetcode question. I was using Python, but somehow, I can not pass the OA, although it ran pretty fine in “run code against your own input”.
Long story short: I decided to use Go to write the solution. While trying to write a helper function (a nested recursive function), I found some interesting things about functions in Go, which I think are worth sharing.
To ignore the needless complex logic, I will use sum
function in this article instead of the original one. It takes a single argument k
, return the sum from natural number k
to 1
. For instance, sum(3)
should be 6
, since3 + 2 + 1
equals to 6
.
Anyway, here is the pattern: a global function called sum
, in which a helper
function is defined, which will invoke it self to produce the result recursively. The sum
function invokes helper
to start the recursion.
#golang #recursion #go #functional-programming