2

I want to be able to return a recursive anonymous function in golang. I have used the code snippet below. Here foo() doesn't work because the anonymous function has no way of referring to itself. bar() works as expected.

What would be the right way of doing this, if at all possible?

package main

import (
    "fmt"
)

func foo() func(int) int {
    return func(x int) int {
        if x == 1 {
            return 1
        }
        return x * func(x-1) // this is where the problem lies
    }
}
func bar() func(int) int {
    return func(x int) int {
        return x * 100 
    }
}

func main() {

    a:= foo()
    b:= bar()
    fmt.Println(a(5))
    fmt.Println(b(5))

}
1

1 Answer 1

6

You can declare f first:

func foo() func(int) int {
    var f func(x int) int
    f = func(x int) int {
        if x == 1 {
            return 1
        }
        return x * f(x-1) 
    }
   return f
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.