Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse String to Int Active Patterns

Tags:

f#

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

like image 470
Torben Clasen Avatar asked Oct 24 '18 21:10

Torben Clasen


1 Answers

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

Something like...

let tryParseInt s = 
    try 
        s |> int |> Some
    with :? FormatException -> 
        None
like image 122
psfinaki Avatar answered Oct 19 '22 03:10

psfinaki