[英]Is this a good example of tail recursion in F#?
let shuffley (numbers:int list) =
let rec loop numbers acc =
match numbers with
| head::tail -> loop (List.rev(tail)) (head::acc)
| [] -> List.rev(acc)
loop numbers []
shuffley [1;2;3;4;5;6;7;8]
I am trying to practice some F# and I was wondering if could be a good example of tail recursion or this is just some nonsense.我正在尝试练习一些 F#,我想知道是否可以作为尾递归的一个很好的例子,或者这只是一些废话。
It is tail-recursive but you are calling List.rev
once per element of your input list -它是尾递归的,但您为输入列表的每个元素调用一次
List.rev
-
shuffley [1;2;3;4;5;6;7;8] = // ...
// numbers acc
loop [1;2;3;4;5;6;7;8] []
loop (List.rev [2;3;4;5;6;7;8]) [1]
loop (List.rev [7;6;5;4;3;2]) [8;1]
loop (List.rev [3;4;5;6;7]) [2;8;1]
loop (List.rev [6;5;4;3]) [7;2;8;1]
loop (List.rev [4;5;6]) [3;7;2;8;1]
loop (List.rev [5;4]) [6;3;7;2;8;1]
loop (List.rev [5]) [4;6;3;7;2;8;1]
loop (List.rev []) [5;4;6;3;7;2;8;1]
List.rev [5;4;6;3;7;2;8;1]
[1;8;2;7;3;6;4;5]
List.rev
is O(n) and so as the input grows, the process for shuffley
grows exponentially. List.rev
是O(n) ,因此随着输入的增长, shuffley
的过程呈指数增长。 Does that make this a good example of tail recursion in F#?这是否使它成为 F# 中尾递归的一个很好的例子? Probably not.
可能不会。 For this particular program, we only need to reverse the input once -
对于这个特定的程序,我们只需要反转输入一次——
let shuffley l =
let rec loop xx yy zz r =
match xx, yy, zz with
| _::_::xx, y::yy, z::zz -> loop xx yy zz (z::y::r)
| _::xx , y::_ , _ -> List.rev (y::r)
| _ -> List.rev r
loop l l (List.rev l) []
printfn "%A" (shuffley [1;2;3;4;5;6;7;8])
// ...
This loop
matches two xx
per iteration and spawns a very straightforward process -这个
loop
每次迭代匹配两个xx
并产生一个非常简单的过程 -
// xx yy zz r
loop [1;2;3;4;5;6;7;8] [1;2;3;4;5;6;7;8] [8;7;6;5;4;3;2;1] []
loop [3;4;5;6;7;8] [2;3;4;5;6;7;8] [7;6;5;4;3;2;1] [8;1]
loop [5;6;7;8] [3;4;5;6;7;8] [6;5;4;3;2;1] [7;2;8;1]
loop [7;8] [4;5;6;7;8] [5;4;3;2;1] [6;3;7;2;8;1]
loop [] [5;6;7;8] [4;3;2;1] [5;4;6;3;7;2;8;1]
List.rev [5;4;6;3;7;2;8;1]
[1;8;2;7;3;6;4;5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.