Lisp - Constants



In LISP, constants are variables that never change their values during program execution. Constants are declared using the defconstant construct.

Syntax

The defun construct is used for defining a function, we will look into it in the Functions chapter.

(defconstant PI 3.141592)

Example - Create Constant

The following example shows declaring a global constant PI and later using this value inside a function named area-circle that calculates the area of a circle.

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; define a constant PI as 3.141592
(defconstant PI 3.141592)

; define a function area-circle
(defun area-circle(rad)
   ; terminate current printing
   (terpri)
   ; print the redius
   (format t "Radius: ~5f" rad)
   ; print the area
   (format t "~%Area: ~10f" (* PI rad rad)))
   
; call the area-cirlce function with argument as 10
(area-circle 10)

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.

Radius:  10.0
Area:   314.1592

We can check if a constant is defined or not using boundp construct.

Syntax

; returns T if constant is available else return Nil
(boundp 'PI)

Example - Check Constant if Exists

The following example shows declaring a global constant PI and later using boundp construct, we're checking existence of PI and in next statement, we're checking another undefined constant.

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; define a constant PI as 3.141592
(defconstant PI 3.141592)

; check if PI constant is defined
(write (boundp 'PI))  ; prints T

; terminate printing
(terpri) 

; check if OMEGA constant is defined
(write (boundp 'OMEGA))  ; prints Nil

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is.

T
NIL
Advertisements