Number Parsing in Haskell
In Haskell, we can parse numbers from strings using various functions from the Text.Read
module and the readMaybe
function from Text.Read.Safe
. Here’s how to do it:
To run the program, save it as number-parsing.hs
and use runhaskell
:
In Haskell, we use the readMaybe
function to parse numbers. This function returns a Maybe
type, which is Just value
if the parsing succeeds, or Nothing
if it fails.
The :: Maybe Type
annotations are used to specify the type we want to parse into. Haskell’s type inference often makes these unnecessary, but they’re included here for clarity.
Note that Haskell doesn’t have a built-in unsigned integer type, so we use regular Integer
for both signed and unsigned cases.
For hexadecimal numbers, Haskell’s readMaybe
automatically recognizes the “0x” prefix.
Error handling in Haskell is done through the Maybe
type. When parsing fails (as in the last example with “wat”), readMaybe
returns Nothing
instead of throwing an exception.
This approach to number parsing in Haskell is type-safe and aligns well with Haskell’s functional programming paradigm.