Recursion 如何将值从递归函数返回到数组

Recursion 如何将值从递归函数返回到数组,recursion,julia,Recursion,Julia,我在从基本递归函数返回值时遇到一些问题,该函数通过重复计算组合。我无法实现如何在combwithrep()函数中将println替换为返回数组。我也未能为此使用任务。最好的结果是在这个值上获得迭代器,但在递归中是不可能的,不是吗 我觉得答案很简单,我不理解递归 这当然不是最优的,但它是功能性的 function nestedLoop(depth::Integer, n::Integer, symbArr, len::Integer, k::Integer, num_arr) for i =

我在从基本递归函数返回值时遇到一些问题,该函数通过重复计算组合。我无法实现如何在
combwithrep()
函数中将
println
替换为返回数组。我也未能为此使用任务。最好的结果是在这个值上获得迭代器,但在递归中是不可能的,不是吗


我觉得答案很简单,我不理解递归

这当然不是最优的,但它是功能性的

function nestedLoop(depth::Integer, n::Integer, symbArr, len::Integer, k::Integer, num_arr)
  for i = k:len
    num_arr[depth-n+1] = symbArr[i]
    n == 1 && println(num_arr)
    (n > 1) && nestedLoop(depth, n-1, symbArr, len, i, num_arr)
  end
end

function combwithrep(symbArr, n::Integer)
  len = length(symbArr)
  num_arr = Array(eltype(symbArr),n)
  nestedLoop(n, n, symbArr, len, 1, num_arr)
end
@time combwithrep(["+","-","*","/"], 3)
julia>函数嵌套的_循环{T combwithrep(['+','-','*','/'],3)
20元素数组{Array{Char,1},1}:
['+','+','+']
['+','+','-']
['+','+','*']
['+','+','/']
['+','-','-']
['+','-','*']
['+','-','/']
['+','*','*']
['+','*','/']
['+','/','/']
['-','-','-']
['-','-','*']
['-','-','/']
['-','*','*']
['-','*','/']
['-','/','/']
['*','*','*']
['*','*','/']
['*','/','/']
['/','/','/']

在尾部递归中包含并返回累加器会给您带来您想要的吗?对于迭代器,遵循创建自己的
类型
长度
开始
下一步
,以及
完成
将是一个很好的练习。@rickhg12hs累加器是一种计数器,如果我们说的话同样。事实上,我需要的是组合本身,而不是计数器。但我似乎没有正确理解你的意思。你能举例说明几行代码吗?@rickhg12hs谈到组合数学中的组合。jl,是的,你关于好的练习是对的。我知道这个迭代器的实现。但它是在没有递归的情况下完成的。我不明白如何在递归的情况下实现它。重写算法当然是可能的,但我试图澄清递归函数的情况。首先,我想回答一个简单的问题:是否可以从递归函数中执行迭代器?谢谢帮助。我已经发布了一种返回所有组合的方法。迭代器是pos有可能,但这可能是一个单独的问题。你是我的英雄;非常感谢。我尝试过做类似的事情,但没有
deepcopy()
。结果令人沮丧。也许我稍后会打开下一个关于递归迭代器的线程。
julia> function nested_loop{T <: Integer, V <: AbstractVector}(depth::T, n::T, symb_arr::V, len::T, k::T, num_arr::V, result::Array{V,1})
           for i = k:len
               num_arr[depth-n+1] = symb_arr[i]
               n == 1 ? push!(result, deepcopy(num_arr)) : nested_loop(depth, n-1, symb_arr, len, i, num_arr, result)
           end
       end
nested_loop (generic function with 1 method)

julia> function combwithrep(symb_arr::AbstractVector, n::Integer)
           len = length(symb_arr)
           num_arr = Array(eltype(symb_arr),n)
           result = Array{typeof(num_arr)}(0)
           nested_loop(n, n, symb_arr, len, 1, num_arr, result)
           return result
       end
combwithrep (generic function with 1 method)

julia> combwithrep(['+', '-', '*', '/'], 3)
20-element Array{Array{Char,1},1}:
 ['+','+','+']
 ['+','+','-']
 ['+','+','*']
 ['+','+','/']
 ['+','-','-']
 ['+','-','*']
 ['+','-','/']
 ['+','*','*']
 ['+','*','/']
 ['+','/','/']
 ['-','-','-']
 ['-','-','*']
 ['-','-','/']
 ['-','*','*']
 ['-','*','/']
 ['-','/','/']
 ['*','*','*']
 ['*','*','/']
 ['*','/','/']
 ['/','/','/']