Number Parsing in Lisp

In Lisp, parsing numbers from strings is a common task. Here’s how to do it:

(defun main ()
  ;; With parse-float, we don't need to specify precision as in Go.
  ;; Lisp automatically uses the most appropriate representation.
  (let ((f (parse-float "1.234")))
    (format t "~A~%" f))

  ;; For parse-integer, we can specify the radix (base) as an optional parameter.
  ;; The default is 10 if not specified.
  (let ((i (parse-integer "123")))
    (format t "~A~%" i))

  ;; parse-integer can recognize hex-formatted numbers when we specify radix 16
  (let ((d (parse-integer "1c8" :radix 16)))
    (format t "~A~%" d))

  ;; There's no built-in parse-unsigned in Common Lisp, but we can use parse-integer
  (let ((u (parse-integer "789")))
    (format t "~A~%" u))

  ;; parse-integer is already the equivalent of Atoi for base-10 integers
  (let ((k (parse-integer "135")))
    (format t "~A~%" k))

  ;; Parse functions signal an error on bad input
  (handler-case
      (parse-integer "wat")
    (error (c)
      (format t "Error: ~A~%" c))))

(main)

Let’s break down the key points:

  1. In Lisp, we use parse-float to parse floating-point numbers. Unlike Go, we don’t need to specify the precision.

  2. parse-integer is used for parsing integers. It can handle different bases by specifying the :radix keyword argument.

  3. Lisp doesn’t have a separate function for parsing unsigned integers. parse-integer is used for both signed and unsigned integers.

  4. There’s no direct equivalent to Go’s Atoi function, but parse-integer serves the same purpose for base-10 integers.

  5. Instead of returning errors, Lisp functions typically signal conditions (a more general concept that includes errors). We use handler-case to catch and handle these conditions.

When you run this program, you should see output similar to this:

1.234
123
456
789
135
Error: The value WAT is not of type INTEGER.

This example demonstrates how to parse various types of numbers from strings in Lisp. The approach is somewhat different from Go, reflecting Lisp’s dynamic typing and condition system, but the core functionality is similar.