Number Parsing in F#

Here’s the translation of the number parsing example from Go to F#:

open System

// F# doesn't have a direct equivalent to Go's strconv package,
// but we can use .NET's built-in parsing functions.

let main() =
    // With Double.Parse, we don't need to specify precision.
    let f = Double.Parse("1.234")
    printfn "%f" f

    // For Int64.Parse, we don't need to specify base or bit size.
    let i = Int64.Parse("123")
    printfn "%d" i

    // To parse hexadecimal, we need to use Int64.Parse with a different NumberStyles.
    let d = Int64.Parse("1c8", System.Globalization.NumberStyles.HexNumber)
    printfn "%d" d

    // UInt64.Parse is available for parsing unsigned integers.
    let u = UInt64.Parse("789")
    printfn "%d" u

    // Int32.Parse is equivalent to Atoi for basic base-10 int parsing.
    let k = Int32.Parse("135")
    printfn "%d" k

    // Parse functions throw exceptions on bad input.
    try
        let _ = Int32.Parse("wat")
    with
    | :? FormatException as e -> printfn "%s" e.Message

main()

This F# code demonstrates number parsing, similar to the original example. Here are the key differences and explanations:

  1. F# uses the .NET framework’s built-in parsing functions instead of a separate strconv package.

  2. Double.Parse is used for floating-point numbers. F# doesn’t require specifying precision like Go’s ParseFloat.

  3. Int64.Parse is used for parsing 64-bit integers. The base is inferred from the string by default.

  4. For hexadecimal parsing, we use Int64.Parse with System.Globalization.NumberStyles.HexNumber.

  5. UInt64.Parse is available for parsing unsigned 64-bit integers.

  6. Int32.Parse is used as a convenience function for basic base-10 integer parsing, similar to Go’s Atoi.

  7. Instead of returning errors, F# parsing functions throw exceptions on bad input. We use a try-with block to catch and print these exceptions.

To run the program, save it as number-parsing.fsx and use the F# interactive or compile and run it:

$ dotnet fsi number-parsing.fsx
1.234000
123
456
789
135
Input string was not in a correct format.

This example demonstrates how to parse numbers from strings in F#, covering floating-point numbers, integers (signed and unsigned), and hexadecimal values. It also shows how to handle parsing errors using exception handling.