用f#递归替换元素

时间:2014-05-17 22:57:48

标签: recursion f#

当我value先行,index在争论列表中排在第二位。以下代码可以使用

let rec replace value index list =
    match index, list with
    | 0, x::xs -> value::xs
    | index, x::xs -> x::replace value (index - 1) xs
    | index, [] -> failwith "index out of range"

let replaceCharArray = replace 'd' 1 ['a';'b';'c']
printfn "%A" replaceCharArray

let reversed_list = replace 100 2 [10;2;35;43;57]
printfn "%A" reversed_list

但是,只要我在参数列表中交换valueindex,我的代码就会中断。我甚至交换了我的参数,所以索引首先出现,当我调用函数时,替换值出现,以防止任何问题,但我仍然遇到问题。

let rec replace index value list =
    match index, list with
    | 0, x::xs -> value::xs
    | index, x::xs -> x::replace value (index - 1) xs
    | index, [] -> failwith "index out of range"

let replacedCharArray = replace 1 'd' ['a';'b';'c']
printfn "%A" replacedCharArray

let replacedNumList = replace 2 100 [10;2;35;43;57]
printfn "%A" replacedNumList

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

问题是你没有交换你递归的参数。将第4行更改为:

| index, x::xs -> x :: replace (index - 1) value xs