Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need Help on Translating C# to F#

Tags:

f#

c#-to-f#

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
like image 809
crystalcoder Avatar asked Jan 30 '23 17:01

crystalcoder


1 Answers

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
    )
like image 127
Anton Schwaighofer Avatar answered Feb 06 '23 17:02

Anton Schwaighofer