Number Parsing in Standard ML
In Standard ML, we can parse numbers from strings using built-in functions or by creating custom parsing functions. Here’s how to do it:
(* We'll use the Real and Int structures for number parsing *)
structure R = Real
structure I = Int
fun main () =
let
(* Parse a float *)
val f = R.fromString "1.234"
val _ = print (R.toString (valOf f) ^ "\n")
(* Parse an integer *)
val i = I.fromString "123"
val _ = print (I.toString (valOf i) ^ "\n")
(* Parse a hexadecimal number *)
val d = I.fromString "0x1c8"
val _ = print (I.toString (valOf d) ^ "\n")
(* Parse an unsigned integer (Standard ML doesn't have unsigned integers, so we use regular integers) *)
val u = I.fromString "789"
val _ = print (I.toString (valOf u) ^ "\n")
(* Convenience function for basic integer parsing (similar to Atoi) *)
fun atoi s = valOf (I.fromString s)
val k = atoi "135"
val _ = print (I.toString k ^ "\n")
(* Handling parsing errors *)
val e = I.fromString "wat"
val _ = case e of
NONE => print "Error: Invalid syntax\n"
| SOME _ => ()
in
()
end
val _ = main()Let’s break down the key points:
In Standard ML, we use the
Real.fromStringfunction to parse floating-point numbers andInt.fromStringfor integers.These functions return an
optiontype, which isSOME valueif parsing succeeds orNONEif it fails. We usevalOfto extract the value, but this will raise an exception if the result isNONE.Standard ML doesn’t have a built-in hexadecimal parser, but
Int.fromStringcan handle hexadecimal strings prefixed with “0x”.There’s no separate unsigned integer type in Standard ML, so we use regular integers for all integer parsing.
We create a simple
atoifunction to mimic the convenience of Go’sAtoifunction.Error handling is done using pattern matching on the
optiontype returned by parsing functions.
To run this program, save it to a file (e.g., number_parsing.sml) and use your Standard ML interpreter or compiler. For example, with MLton:
$ mlton number_parsing.sml
$ ./number_parsing
1.234
123
456
789
135
Error: Invalid syntaxThis example demonstrates basic number parsing in Standard ML. The language doesn’t have as many built-in parsing functions as some other languages, so for more complex parsing tasks, you might need to implement custom parsing logic or use additional libraries.