以下代码用于替换数组的第一个元素, 但我想指定值1而不是值0到 删除数组的第一个元素。
let rec replace index value list =
match index, list with
| 0, x::xs -> value::xs
| index, x::xs -> x::replace (index - 1) value xs
| index, [] -> failwith "index out of range"
let replaceCharArray = replace 0 'd' ['a';'b';'c']
printfn "%A" replaceCharArray
我修改了上面的代码工作代码,以便我可以这样做,但现在我 我的范围超出范围。
let rec replace index value list =
match index, list with
| 0, x::xs -> value::xs
| index, x::xs -> x::replace ((index - 1) - 1) value xs
| index, [] -> failwith "index out of range"
let replaceCharArray = replace 1 'd' ['a';'b';'c']
printfn "%A" replaceCharArray
有人可以帮我弄清楚为什么我会超出范围 异常?
答案 0 :(得分:1)
let rec replace index value list =
match index, list with
| 0, _ -> failwith "index out of range"
| 1, x::xs -> value::xs
| index, x::xs -> x::replace (index - 1) value xs
| index, [] -> failwith "index out of range"