Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indexes of elements of an array with certain values

Tags:

f#

Consider I have an array of options like [|Some 1;Some0;None;None;Some0|] and i am going to get the indexes of elements with None value, in this case the correct answer would be [|2;3|].

My current idea is to change the array to a list and then go throw it using recursive function but in this case i will need mutable value to compute index, and i do not want to use mutable?

Is there any other solution

like image 798
Sal-laS Avatar asked Oct 25 '25 02:10

Sal-laS


1 Answers

Here's another solution:

[|Some 1;Some 0;None;None;Some 0|]
    |> Array.indexed
    |> Array.filter (fun (i, x) -> x.IsNone)
    |> Array.map fst

As an optimization last 2 lines can be replaced by a single |> Array.choose (function (i, None) -> Some i | _ -> None).

And here's another way using sequence expressions:

let x = [|Some 1;Some 0;None;None;Some 0|]
[|for i = 0 to x.Length-1 do
     if x.[i].IsNone then yield i|]
like image 170
Gus Avatar answered Oct 26 '25 21:10

Gus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!