F#尾递归调用

我有这样的代码:

let rec collect ( t : BCFile list ) ( acc : Set<BCFile> ) : Set<BCFile> =
    match t with
    | [] -> acc
    | hr::tl -> collect ( tl ) ( Set.union acc ( FindSourceFilesForTarget ( hr ) ) )
let s = collect (Set.toList targets) Set.empty

它看起来应该是尾递归,但它不是(看着IL)。 任何想法为什么它没有编译使用尾递归?


据我所知, collect函数实际上是尾递归的。 第一种情况显然只是返回acc 。 第二种情况首先调用FindSourceFilesForTarget ,然后调用Set.union然后返回。 你可以重写它如下(更清楚地显示尾递归):

| hr::tl -> 
    let sources = FindSourceFilesForTarget hr
    let acc = Set.union acc sources
    collect tl

因为这只是一个调用自己的函数,所以编译器会将其优化为一个循环。 这是编译代码的外观(当你使用反射器将其转换为C#时):

public static FSharpSet<int> collect(FSharpList<int> t, FSharpSet<int> acc) {
  while (true) {
    FSharpList<int> fSharpList = t;
    if (fSharpList.TailOrNull == null) break;
    // The following corresponds to the second case 
    FSharpList<int> tl = fSharpList.TailOrNull;
    int hr = fSharpList.HeadOrDefault;
    // Variables 'acc' and 't' are mutated (instead of calling the function)
    acc = SetModule.Union<int>(acc, Program.FindSourceFilesForTarget<int>(hr));
    t = tl;
  }
  return acc;
}

在稍微不相关的说明中,您也可以使用标准库函数来表达它:

t |> Seq.map FindSourceFilesForTarget |> Set.unionMany
链接地址: http://www.djcxy.com/p/14157.html

上一篇: F# tail recursive call

下一篇: How does F# inline work?