Return recursive anonymous functions in golang

bossman

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))

}
Burak Serdar

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
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related