有没有办法将索引作为参数传递给映射到数组的函数?
Is there a way to pass index as parameter to function being mapped onto an array?
我有一个函数 myFunction
,我正在将其映射到数组 input
。我想引用 myFunction
中 array
元素的索引。我查看了一些网站,例如 https://docs.microsoft.com/en-us/dotnet/fsharp/ and https://fsharpforfunandprofit.com/,但找不到任何将索引传递给映射函数的内容。
以下是我正在测试的成员:
// functions
static member Whosebug0 (input :int[]) :int[] =
let myFunction (x :int) :int = x + x
input |> Array.map myFunction
// incorrect syntax
static member Whosebug1 (input :int[]) :int[] =
let myFunction (index :int, x :int) :int = x + x + index
Map myFunction <| (seq {0 .. input.Length}, input)
您可以使用 Array.mapi
,它完全满足您的需求:
static member Whosebug1 (input :int[]) :int[] =
let myFunction index x = x + x + index
input |> Array.mapi myFunction
或者,您可以先使用 Array.indexed
用索引注释每个元素,然后映射成对:
static member Whosebug1 (input :int[]) :int[] =
let myFunction (index, x) = x + x + index
input |> Array.indexed |> Array.map myFunction
我有一个函数 myFunction
,我正在将其映射到数组 input
。我想引用 myFunction
中 array
元素的索引。我查看了一些网站,例如 https://docs.microsoft.com/en-us/dotnet/fsharp/ and https://fsharpforfunandprofit.com/,但找不到任何将索引传递给映射函数的内容。
以下是我正在测试的成员:
// functions
static member Whosebug0 (input :int[]) :int[] =
let myFunction (x :int) :int = x + x
input |> Array.map myFunction
// incorrect syntax
static member Whosebug1 (input :int[]) :int[] =
let myFunction (index :int, x :int) :int = x + x + index
Map myFunction <| (seq {0 .. input.Length}, input)
您可以使用 Array.mapi
,它完全满足您的需求:
static member Whosebug1 (input :int[]) :int[] =
let myFunction index x = x + x + index
input |> Array.mapi myFunction
或者,您可以先使用 Array.indexed
用索引注释每个元素,然后映射成对:
static member Whosebug1 (input :int[]) :int[] =
let myFunction (index, x) = x + x + index
input |> Array.indexed |> Array.map myFunction