Constants in Lisp

Go by Example: Constants

Go supports constants of character, string, boolean, and numeric values.

(defpackage :constants
  (:use :cl))

(in-package :constants)

(defconstant +s+ "constant")

(defun main ()
  (format t "~a~%" +s+)

  (defconstant +n+ 500000000)
  (defconstant +d+ (/ 3e20 +n+))
  
  (format t "~a~%" +d+)
  (format t "~a~%" (float +d+))
  (format t "~a~%" (sin +n+)))

A const statement can appear anywhere a var statement can.

(defconstant +n+ 500000000)

Constant expressions perform arithmetic with arbitrary precision.

(defconstant +d+ (/ 3e20 +n+))
(format t "~a~%" +d+)

A numeric constant has no type until it’s given one, such as by an explicit conversion.

(format t "~a~%" (float +d+))

A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, here math.sin expects a float64.

(format t "~a~%" (sin +n+))

To run the program, put the code in a file and load it in a Common Lisp environment.

(load "constants.lisp")
(constants:main)

When executed, the program outputs:

constant
6e+11
6.0e+11
-0.28470407323754404

Now that we can work with constants in Common Lisp, let’s learn more about the language.