【发布时间】:2018-05-04 12:15:49
【问题描述】:
我有一对(共同?)递归函数,它们处理一个元组列表,并根据一些开始和结束条件将它们折叠成批次。
我不怎么做f#,所以我可能很愚蠢。
我已经修改了一个简单的非尾递归版本,通过显式引入构成当前折叠状态的“tot”参数,我认为这是尾递归,但在大输入时我得到了可怕的堆栈溢出....(在调试器和(调试).exe 中)
可能有一种更好的方法可以将其作为显式折叠...但这几乎不是重点,重点是为什么它看起来不是尾递归?
let rec ignoreUntil2 (xs : List<(string * string)>) tot = //: List<(string * string)> -> List<List<(string * string)>> -> List<List<(string * string)>> =
match xs with
| [] -> tot
| ((s1,s2)::tail) ->
if s2.StartsWith("Start importing record: Product") then
takeUntil2 [] ((s1,s2)::tail) tot
else
ignoreUntil2 tail tot
and takeUntil2 acc xs tot = // : List<(string * string)> -> List<(string * string)> -> List<List<(string * string)>> -> List<List<(string * string)>> =
match xs with
| [] -> acc :: tot
| ((s1,s2)::tail) ->
let newAcc = ((s1,s2)::acc)
if s2.StartsWith("Finished importing record: Product") then
ignoreUntil2 tail (newAcc :: tot)
else
takeUntil2 newAcc tail tot
【问题讨论】:
标签: recursion f# tail-recursion