I have this code sample in C#, which outputs index and value from the array:
static void Sample_Select_Lambda_Indexed()
{
string[] arr = { "my", "three", "words" };
var res = arr.Select((a, i) => new
{
Index = i,
Val = a
});
foreach(var element in res)
Console.WriteLine(String.Format("{0}: {1}", element.Index, element.Val));
}
Output is:
0: my
1: three
2: words
I want to make a similar query in F#, and have started like this:
let arr = [|"my"; "three"; "words"|]
let res = query {
for a in arr do
// ???
}
How would I finish this LINQ query?
You can use Seq.mapi
:
let res = arr |> Seq.mapi (fun i a -> ...)
or just use Seq.iteri
directly:
arr |> Seq.iteri (fun i v -> printfn "%i: %s" i v)
or just:
arr |> Seq.iteri (printfn "%i: %s")
Here's one way:
let arr = [|"my"; "three"; "words"|]
let res = Array.mapi(fun index value -> (index, value)) arr
for (index, value) in res do
printfn "%i: %s" index value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With