我刚刚开始使用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块中调用一个函数,所以我假设我犯了一个错误。关于我的代码的任何其他提示都是受欢迎的。
答案 0 :(得分:1)
您的代码:
(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))))
答案 1 :(得分:1)
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" ...))