2014-05-17 35 views
-1

當我有value先去,index在參數列表中排在第二位。下面的代碼工作用f遞歸替換元素#

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 

有人能幫我解決這個問題嗎?

回答

2

問題是你沒有交換你遞歸的參數。將第4行更改爲:

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