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:
In Lisp, we use
parse-floatto parse floating-point numbers. Unlike Go, we don’t need to specify the precision.parse-integeris used for parsing integers. It can handle different bases by specifying the:radixkeyword argument.Lisp doesn’t have a separate function for parsing unsigned integers.
parse-integeris used for both signed and unsigned integers.There’s no direct equivalent to Go’s
Atoifunction, butparse-integerserves the same purpose for base-10 integers.Instead of returning errors, Lisp functions typically signal conditions (a more general concept that includes errors). We use
handler-caseto 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.