colinfang
colinfang

Reputation: 21757

how to do Array.tryFind with index?

a simple example of what I would like to do is

 Array.tryFind (fun elem index -> elem + index = 42) array1  //not valid

Since there is no break or continue, i find it hard to do it manually even in a for loop

Upvotes: 2

Views: 958

Answers (3)

pad
pad

Reputation: 41290

Similar with @gradbot's answer, you could define a module function along the line of mapi, iteri which works on arrays, lists and sequences.

module Seq =
    let tryFindi fn seq =
        seq |> Seq.mapi (fun i x -> i, x)
            |> Seq.tryFind (fun (i, x) -> fn i x)
            |> Option.map snd

// Usage
let res = [|1;1;40;4;2|] |> Seq.tryFindi (fun i el -> i + el = 42)

Upvotes: 4

gradbot
gradbot

Reputation: 13862

Whenever I find something I need missing from the built in functions, I just add it! I always have a file called Helpers.fs where I keep all of these. Just make sure to give it a good name.

module Array =
    let tryFindWithIndex fn (array : _[]) =
        let rec find index =
            if index < array.Length then
                if fn array.[index] index then
                    Some(array.[index])
                else
                    find (index + 1)
            else
                None
        find 0

Example use.

[|1;1;40;4;2|]
|> Array.tryFindWithIndex (fun elem index -> elem + index = 42)
|> printf "%A"

Outputs

Some 40

Upvotes: 3

desco
desco

Reputation: 16782

Something like this (disclaimer: typing in browser - may contain errors)

array |> Seq.mapi (fun i el -> i + el) |> Seq.tryFind ((=)42)

Upvotes: 2

Related Questions