Nicholas Sabadicci
Nicholas Sabadicci

Reputation: 41

Recursive Inner Functions Golang

Recursive inner function declaration golang

Is it supposed to be ugly?

I'm currently trying to write a recurisve DFS for a leetcode problem (new to Golang)

Doesn't Run:

when I try to create and declare my inner function like this:

outerFunction (node *TreeNode, target int) bool {
  checkSolutions := func(node *TreeNode, total int) bool {
        // ... DFS algo
        checkSolutions(node.Left)
        checkSolutions(node.Right)
    }
    
  return checkSolution(root, 0)
}

I don't have access to the inner function during the recursive call and get an error! However when I declare the function as a variable first (below) it runs

Runs:
outerFunction (node *TreeNode, target int) bool {
  var checkSolution func(*TreeNode, int) bool
  checkSolutions = func(node *TreeNode, total int) bool {
        // ... DFS algo
        checkSolutions(node.Left)
        checkSolutions(node.Right)
    }
    
  return checkSolution(root, 0)
}

Is this the cleanest way to declare recursive inner functions in Go? For some reason it feels a little bit verbose to me so I just wanted to make this post to see if there's any Golang syntactic sugar intended for this situation that I'm missing.

Upvotes: 3

Views: 393

Answers (2)

advay rajhansa
advay rajhansa

Reputation: 1247

In a gist, this is the best you can get. There is nothing better here.

In the firat case, you can clearly see that the function checkSolutions is not decleared. Hence, when you use that inside the declaration, go compiler has no idea what that function is and what is it supposed to do (params and returns).

outerFunction (node *TreeNode, target int) bool {
  checkSolutions := func(node *TreeNode, total int) bool {
        // ... DFS algo
        checkSolutions(node.Left)    // Is not decleared yet to be used
        checkSolutions(node.Right)
    }
    
  return checkSolution(root, 0)
}

In other case, when you have defined what it is supposed to do, compiler can understand the definitions and proceed accordingly.

Upvotes: 1

Shailesh Suryawanshi
Shailesh Suryawanshi

Reputation: 1270

I believe that in the snippet1, before assigning value all the statements to the right of := has to be evaluated. Once the evaluation is complete it can be assigned memory.

In the snippet1, we are calling the function checkSolution before it exists. Therefore it throws error.

Whereas in the snippet2 var checkSolution func(*TreeNode, int) bool initializes and assigns memory. So it is in existence, which can be called by the inner function of checkSolution

I believe that this is the best way to achieve the recursion here.

Upvotes: 0

Related Questions