Number Parsing in Idris
Here’s the translation of the number parsing example from Go to Idris, formatted in Markdown suitable for Hugo:
This program demonstrates number parsing in Idris. Here’s a breakdown of the code:
We use
parseDouble
from theData.String
module to parse floating-point numbers. It returns aMaybe Double
, so we usefromMaybe
to provide a default value if parsing fails.For parsing integers, we use
parseInteger
which takes a base as its first argument. We use base 10 for decimal numbers.We can parse hexadecimal numbers by using
parseInteger
with base 16.For parsing unsigned integers, Idris provides
parsePositive
.Idris allows us to use
cast
for basic type conversions, including parsing strings to integers.When parsing fails, these functions return
Nothing
. We demonstrate this by trying to parse an invalid input “wat”.
Note that Idris’s approach to error handling is different. Instead of returning an error value, Idris uses the Maybe
type to represent the possibility of parsing failure.
To run this program, save it as NumberParsing.idr
and use the Idris interpreter:
This example showcases Idris’s strong type system and its approach to handling potential failures in parsing operations.