【发布时间】:2018-01-17 10:13:25
【问题描述】:
所以我有这个似乎对非尾调用友好的函数,对吧?
let rec insertFooInProperPosition (foo: Foo) (bar: list<Foo>): list<Foo> =
match bar with
| [] -> [ foo ]
| head::tail ->
if (foo.Compare(head)) then
foo::bar
else
head::(insertFooInProperPosition foo tail)
然后我试图弄清楚如何使用累加器,以便函数完成的最后一件事是调用自身,我想出了这个:
let rec insertFooInProperPositionTailRec (foo: Foo) (headListAcc: list<Foo>) (bar: list<Foo>): list<Foo> =
match bar with
| [] -> List.concat [headListAcc;[ foo ]]
| head::tail ->
if (foo.Compare(head)) then
List.concat [headListAcc; foo::bar]
else
insertFooInProperPosition foo (List.concat [headListAcc;[head]]) tail
let rec insertFooInProperPosition (foo: Foo) (bar: list<Foo>): list<Foo> =
insertFooInProperPositionTailRec foo [] bar
但是,据我了解,使用 List.concat 会使这个函数的效率大大降低,对吧?那么我该如何正确地进行这种转换呢?
【问题讨论】:
标签: recursion f# tail-recursion tail-call-optimization tail-call