I need help on translating custom extension for IndexOfAny for string as existing framework does not have IndexOfAny that matching string values. Already translated my own. However I have no idea how to break out of loop by return value. Any idea how to break out of loop or better solution. Below is my translation.
C#
public static int IndexOfAnyCSharp(this string str, string[] anyOff) {
    if (str != null && anyOff != null)
        foreach (string value in anyOff) {
            int index = str.IndexOf(value);
            if (index > -1) return index;
        }
    return -1;
}
F#
[<Extension>]
static member public IndexOfAnyFSharp(str:string, anyOff:string[]) =
    match str <> null && anyOff <> null with
    | true ->
        let mutable index = -1
        for value in anyOff do
            if index = -1 then
                index <- str.IndexOf(value)
        index
    | false -> -1
                Seq.tryFind is your friend. A basic building block would be something like
let IndexOfAny (s: string, manyStrings: string seq) = 
    manyStrings
    |> Seq.map (fun m -> s.IndexOf m)
    |> Seq.tryFind (fun index -> index >= 0)
This will return None if nothing matches - this is more idiomatic F# than returning -1: The compiler will force you to think about the case that nothing matches. 
Update: You may prefer:
let IndexOfAny (s: string, manyStrings: string seq) = 
    manyStrings
    |> Seq.tryPick (fun m ->
        match s.IndexOf m with
        | -1 -> None
        | i -> Some i
    )
                        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