Number Parsing in Elm
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Elm.
module Main exposing (main)
import Html exposing (Html, div, text)
main : Html msg
main =
div []
[ parseFloat
, parseInt
, parseHex
, parseUInt
, parseBasicInt
, parseInvalidInt
]
parseFloat : Html msg
parseFloat =
case String.toFloat "1.234" of
Just f ->
text ("Parsed float: " ++ String.fromFloat f)
Nothing ->
text "Failed to parse float"
parseInt : Html msg
parseInt =
case String.toInt "123" of
Just i ->
text ("Parsed int: " ++ String.fromInt i)
Nothing ->
text "Failed to parse int"
parseHex : Html msg
parseHex =
case String.toInt "0x1c8" of
Just d ->
text ("Parsed hex: " ++ String.fromInt d)
Nothing ->
text "Failed to parse hex"
parseUInt : Html msg
parseUInt =
case String.toInt "789" of
Just u ->
text ("Parsed uint: " ++ String.fromInt u)
Nothing ->
text "Failed to parse uint"
parseBasicInt : Html msg
parseBasicInt =
case String.toInt "135" of
Just k ->
text ("Parsed basic int: " ++ String.fromInt k)
Nothing ->
text "Failed to parse basic int"
parseInvalidInt : Html msg
parseInvalidInt =
case String.toInt "wat" of
Just _ ->
text "Unexpectedly parsed invalid int"
Nothing ->
text "Failed to parse invalid int, as expected"
In Elm, we use the String.toFloat
and String.toInt
functions for parsing numbers from strings. These functions return a Maybe
type, which we handle using pattern matching.
For parseFloat
, we use String.toFloat
to parse a floating-point number.
For parseInt
, parseHex
, parseUInt
, and parseBasicInt
, we use String.toInt
. Elm’s String.toInt
function automatically handles different bases, including hexadecimal numbers prefixed with “0x”.
Elm doesn’t have separate functions for parsing signed and unsigned integers, so we use String.toInt
for both cases.
The parseInvalidInt
function demonstrates how Elm handles parsing errors. When given an invalid input, String.toInt
returns Nothing
, which we can handle in our pattern matching.
To run this program, you would typically compile it to JavaScript and run it in a web browser. The output would be displayed as HTML elements on the page.
Note that Elm’s approach to parsing is more type-safe than the original example, as it uses the Maybe
type to represent the possibility of parsing failure, rather than returning a separate error value.