Common Lisp let 函数

Common Lisp let function

我刚刚开始使用 Common Lisp 进行编程,然后回过头来浏览我在之前的一些 类 中编写的程序以进行学习,但我无法理解我的代码中的问题。

(defun input-1 ()
       (defvar *message* (read-line))
       (defvar *a-value* (parse-integer(read-line)))
       (defvar *b-value* (parse-integer(read-line))))

(defun alphabet (list " " "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m"
         "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"))

(defun alphabet-num (list 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
             20 21 22 23 24 25 26 27 28 29))
;(defun inverse (value)
;  (let ((x 0))
;    (loop while (< x 29)
;    (print x))))

(defun inverse (value)
       (dotimes (x 28)
           (when (equal (mod (* x value) 29) 1)
             (return-from inverse x))))

(defun get-int (string)
  (getf (position string alphabet) alphabet-num))

(defun get-string (int)
  (getf (position int alphabet) alphabet))

(defun cipher-calc (character)
  (let ((c-int (get-int character))
    (f-char ""))
    (setf c-int (* *a-value* (- c-int *b-value*)))
    (setf f-char (get-string (mod (abs c-int) 29)))))

但是,我遇到了这个错误

; in: DEFUN CIPHER-CALC
;     (* *A-VALUE* (- C-INT *B-VALUE*))
; 
; caught WARNING:
;   undefined variable: *A-VALUE*

;     (- C-INT *B-VALUE*)
; 
; caught WARNING:
;   undefined variable: *B-VALUE*

;     (GET-INT CHARACTER)
; 
; caught STYLE-WARNING:
;   undefined function: GET-INT

;     (GET-STRING (MOD (ABS C-INT) 29))
; 
; caught STYLE-WARNING:
;   undefined function: GET-STRING
; 
; compilation unit finished
;   Undefined functions:
;     GET-INT GET-STRING
;   Undefined variables:
;     *A-VALUE* *B-VALUE*
;   caught 2 WARNING conditions
;   caught 2 STYLE-WARNING conditions

我很难相信您不能在 let 块内调用函数,所以我假设我犯了一个错误。欢迎对我的代码提出任何其他提示。

您的代码:

(defun input-1 ()
  (defvar *message* (read-line))
  (defvar *a-value* (parse-integer(read-line)))
  (defvar *b-value* (parse-integer(read-line))))

DEFVAR 应该用在顶层而不是函数内部。在这种情况下,变量将在函数运行时定义。但是当你只是编译、评估或加载这样一个函数时,变量并没有被定义。因此,编译器稍后会警告您的代码中这些变量未定义。

当在顶层使用DEFVAR时,Lisp会识别出有变量定义。

(defvar *message*)
(defvar *a-value*)
(defvar *b-value*))

(defun input-1 ()
  (setf *message* (read-line))
  (setf *a-value* (parse-integer (read-line)))
  (setf *b-value* (parse-integer (read-line))))

defvar 并不像您想象的那样。它确保变量存在,如果恰好不存在,则将其绑定到第二个参数。因此:

(defvar *test* 5)
(defvar *test* 10) ; already exist, has no effect
*test* ; ==> 5

你可以做的是在你的文件顶部像这样定义它们并在你的函数中使用 setf:

(defvar *message*)

(defun input-1 ()
       (setf *message* (read-line))
       ...)

毕竟设置就是你在做什么。您将函数和变量与 alphabet 混合在一起。在这里你可以使用 defparameter。它类似于 defvar 但它总是在您加载文件时覆盖:

(defparameter *alphabet* (list " " "a" "b" ...))