Number Parsing in Idris
Here’s the translation of the number parsing example from Go to Idris, formatted in Markdown suitable for Hugo:
import Data.String
main : IO ()
main = do
-- With parseDouble, we can parse floating-point numbers
let f = fromMaybe 0.0 $ parseDouble "1.234"
putStrLn $ show f
-- For parseInt, we can specify the base (10 for decimal)
let i = fromMaybe 0 $ parseInteger 10 "123"
putStrLn $ show i
-- parseInt will recognize hex-formatted numbers with base 16
let d = fromMaybe 0 $ parseInteger 16 "1c8"
putStrLn $ show d
-- For parsing unsigned integers, we can use parsePositive
let u = fromMaybe 0 $ parsePositive "789"
putStrLn $ show u
-- For basic base-10 integer parsing, we can use cast
let k = cast "135" :: Integer
putStrLn $ show k
-- Parse functions return a Maybe type, which is None on bad input
let e = parseInteger 10 "wat"
putStrLn $ show eThis program demonstrates number parsing in Idris. Here’s a breakdown of the code:
We use
parseDoublefrom theData.Stringmodule to parse floating-point numbers. It returns aMaybe Double, so we usefromMaybeto provide a default value if parsing fails.For parsing integers, we use
parseIntegerwhich takes a base as its first argument. We use base 10 for decimal numbers.We can parse hexadecimal numbers by using
parseIntegerwith base 16.For parsing unsigned integers, Idris provides
parsePositive.Idris allows us to use
castfor 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:
$ idris NumberParsing.idr -o number-parsing
$ ./number-parsing
1.234
123
456
789
135
NothingThis example showcases Idris’s strong type system and its approach to handling potential failures in parsing operations.