Number Parsing in F#
Here’s the translation of the number parsing example from Go to F#:
This F# code demonstrates number parsing, similar to the original example. Here are the key differences and explanations:
F# uses the .NET framework’s built-in parsing functions instead of a separate
strconv
package.Double.Parse
is used for floating-point numbers. F# doesn’t require specifying precision like Go’sParseFloat
.Int64.Parse
is used for parsing 64-bit integers. The base is inferred from the string by default.For hexadecimal parsing, we use
Int64.Parse
withSystem.Globalization.NumberStyles.HexNumber
.UInt64.Parse
is available for parsing unsigned 64-bit integers.Int32.Parse
is used as a convenience function for basic base-10 integer parsing, similar to Go’sAtoi
.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:
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.