📜  LISP 中的常量

📅  最后修改于: 2022-05-13 01:55:48.939000             🧑  作者: Mango

LISP 中的常量

在 LISP 中,所有常量都是全局变量。在整个程序执行过程中,常量的值永远不会改变。

在 LISP 中定义常量:

使用DEFCONSTANT构造定义新的全局常量
句法:

(defconstant name initial-value-form 
   "documentation-string")

例子:

让我们创建一个全局常量,其值将包含衬衫的费率

(defconstant shirt-rate 575
  "shirt-rate is having a constant value of 575")

现在让我们创建一个函数,通过将衬衫数量作为输入,然后将其乘以我们之前定义的常量衬衫费率来计算总账单

(defun calc-total-bill (n)
  "Calculates the total bill by multiplying the number of shirts purchased with its constant rate"
  (* shirt-rate n))

让我们调用这个函数



(format t "Total number of shirts purchased : 7~%")
(format t "Price of each shirt : ~2d~%" shirt-rate)
(format t "Total bill amount is : ~2d~%" (calc-total-bill 7))

代码:

Lisp
(defconstant shirt-rate 575
  "shirt-rate is having a constant value of 575")
  
(defun calc-total-bill (n)
  "Calculates the total bill by multiplying the number of
   shirts purchased with its constant rate"
  (* shirt-rate n))
  
(format t "Total number of shirts purchased : 7~%")
(format t "Price of each shirt : ~2d~%" shirt-rate)
(format t "Total bill amount is : ~2d~%" (calc-total-bill 7))


Lisp
(write (boundp 'shirt-rate))
(terpri)
(write (boundp 'rate))


输出 :

我们可以使用boundp谓词检查某个符号是否是全局变量或常量的名称,因为它是谓词,如果找到具有特定名称的常量则返回T ,否则将返回NIL

例如,在我们的程序中,我们定义了一个恒定的衬衫率,所以让我们运行这个

Lisp

(write (boundp 'shirt-rate))
(terpri)
(write (boundp 'rate))

输出 :

T
NIL

正如预期的那样,它在找到恒定衬衫速率时返回T ,但在程序中找不到恒定速率时返回NIL