我写了这段代码来递归复制我的列表:
let sp = [2;4;6;8;10]
let copy (s1:'a list) =
let rec copy acc ind =
if(ind>=0) then
copy (s1.[ind]::acc) (ind-1)
else acc
copy [] (s1.Length-1)
sp |> copy |> printfn "%A"
Run Code Online (Sandbox Code Playgroud)
如何使这段代码更容易?
执行列表查找(以及获取列表的长度)效率不高,因为库需要遍历整个列表(或前N个元素).出于这个原因,在F#中这样做并不是真正的惯用语.
你仍然可以保留代码的大部分结构,但是改变它有点像这样:
let copy input =
let rec copy acc input =
match input with
| [] -> List.rev acc
| x::xs -> copy (x::acc) xs
copy [] input
Run Code Online (Sandbox Code Playgroud)
变化是:
acc相反的顺序追加项目,我们调用List.rev结束时反转结果(这是使用列表时的标准技巧)