TryParse String to Int Active Patterns

Viewed 3656

Hello SO I am currently trying to parse a string to an Int using active Patterns and the Int.TryParse Method. Using the old examples from 2012 it used to work something like this:

let (|Int|_|) str =
    match System.Int32.TryParse str with
    | true,int -> Some int
    | _ -> None

but now I'm getting an error telling me that the right overload of TryParse() can not be choosen. Annotating the str as a string the error persists. I hope any one of you could help me with this simple problem, thanks in advance.

Some additional Information: I am trying this using FSharp.Core 4.5.2 and .Net Core 2.1.

The Error:

FS0041 A unique overload for method 'TryParse' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: Int32.TryParse(s: ReadOnlySpan<char>, result: byref<int>) : bool, Int32.TryParse(s: string, result: byref<int>) : bool

3 Answers

Found my own mistake with the Help of Jestar342 on Reddit:

let (|Int|_|) (str:string) =
    match System.Int32.TryParse str with
    | true,int -> Some int
    | _ -> None

changing str to (str:string) fixes this error.

Consider also using a more idiomatic F# built-in int function.

Something like...

let tryParseInt s = 
    try 
        s |> int |> Some
    with :? FormatException -> 
        None

The Span type was recently introduced into .Net.

That is one drawback of type inference and overloaded functions: it can break existing code. Type annotation is the solution.

Related