Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a LINQ query to include index in Select with F#

Tags:

c#

linq

f#

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?

like image 937
brinch Avatar asked Dec 10 '22 23:12

brinch


2 Answers

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")
like image 116
Lee Avatar answered Jan 21 '23 01:01

Lee


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
like image 40
Andrew Whitaker Avatar answered Jan 21 '23 02:01

Andrew Whitaker