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:

import Text.Read (readMaybe)

main :: IO ()
main = do
    -- Parse a float
    let f = readMaybe "1.234" :: Maybe Double
    print f

    -- Parse an integer
    let i = readMaybe "123" :: Maybe Integer
    print i

    -- Parse a hexadecimal number
    let d = readMaybe "0x1c8" :: Maybe Integer
    print d

    -- Parse an unsigned integer (same as regular integer in Haskell)
    let u = readMaybe "789" :: Maybe Integer
    print u

    -- Parse a basic base-10 integer
    let k = readMaybe "135" :: Maybe Int
    print k

    -- Demonstrate error handling
    let e = readMaybe "wat" :: Maybe Int
    print e

To run the program, save it as number-parsing.hs and use runhaskell:

$ runhaskell number-parsing.hs
Just 1.234
Just 123
Just 456
Just 789
Just 135
Nothing

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.