递归而不是循环

梅尔路:

我是Go编程的新手,那么如何在此代码中实现递归而不是for循环?

package main

import (
    "fmt"
)

func main() {
    var n int
    fmt.Scan(&n)
    set(n)
}

func set(n int) {
    a := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    fmt.Println(a)
}
叶蜂

我不确定您要递归什么。但是,据我所知,您的问题是将for循环更改为递归,因此我以函数式编程风格将其转换为闭包中的尾部递归。

func set(n int) {
    a := make([]int, n)
    var setRecursive func(int) // declare a function variable, which take an int as param.
    setRecursive = func(i int) { // set the function in closure, so a and n is available to it.
        if i == 0 { // end point of the recursion, return.
            return
        }
        Scan(&a[n-i]) // Use fmt.Scan out of playground
        setRecursive(i - 1) // tail recursion.
    }
    setRecursive(n) // call the function, start the recursion.
    fmt.Println(a)
}

如果您想简化此事,可以删除闭合部分并将线移到该线的Scan(&a[n-i])后面setRecursive(n),如下所示:

func SetRecursive(a []int, n int) {
    if n==0 {
        return
    }

    SetRecursive(a,n-1) // recurse first, so we can scan in the right order.
    Scan(&a[n-1])
}

游乐场:https : //play.golang.org/p/0io190tyviE

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章