使用不同的值更改列表的特定元素

时间:2018-08-10 11:16:51

标签: f#

我正在尝试编写一个函数,该函数接受一个int元组,一个int列表和一个最大值,并使用该函数来更新该元组中1的实例-我知道如何使用List.map来检查并更新每个实例,但不知道如何遍历并用不同的值替换列表中的第一个或最后一个实例

let rower (t:int * int list) (size: int) : int list = 
    let (count, row) = t

    let first = count + 1
    let last = (size * size) - count

    let ret = 
        row 
        |> List.map (* how do I change the first instance of 1? *)
        |> List.map (* how do I change the last instance of 1? *)

    printfn "%A first %d last %d" t first last

    row

let ``the first test`` = 
    let expected = [0; 2; 0; 8; 0]
    let actual = rower (1, [0; 1; 0; 1; 0]) 3
    expected = actual 

printfn "%b" ``the first test``

1 个答案:

答案 0 :(得分:3)

rmunn确切解释了如何做-见下文:

let rower (t:int* int list) (size: int) : int list = 
    let (count, row) = t

    let first = count + 1
    let last = (size * size) - count

    let i = row |> List.findIndex (fun x -> x = 1)
    let j = row |> List.findIndexBack (fun x -> x = 1)

    row 
    |> List.mapi (fun idx x -> 
        if idx = i then first 
        elif idx = j then last
        else x)

let ``the first test`` = 
    let expected = [0; 2; 0; 8; 0]
    let actual = rower (1, [0; 1; 0; 1; 0]) 3
    expected = actual 

printfn "%b" ``the first test``
相关问题