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:

  1. In Standard ML, we use the Real.fromString function to parse floating-point numbers and Int.fromString for integers.

  2. These functions return an option type, which is SOME value if parsing succeeds or NONE if it fails. We use valOf to extract the value, but this will raise an exception if the result is NONE.

  3. Standard ML doesn’t have a built-in hexadecimal parser, but Int.fromString can handle hexadecimal strings prefixed with “0x”.

  4. There’s no separate unsigned integer type in Standard ML, so we use regular integers for all integer parsing.

  5. We create a simple atoi function to mimic the convenience of Go’s Atoi function.

  6. Error handling is done using pattern matching on the option type 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 syntax

This 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.