首页 > 解决方案 > 如何在lisp中进行循环?

问题描述

刚开始学习和编码 lisp,我正在尝试创建一个程序,该程序将持续接受一个数字,并且仅当且仅当最后一个输入数字是前一个数字的两倍时才停止。

这是我的代码

 


----------


(let((a 0)
     (b 0)
     (count 0))
(loop
   (= a b))
   (princ"Enter Number: ")
   (defvar a(read))
   (format t "~% a = ~d" a)
   (setq count (1+ count))
(while
   (!= b(* a 2) || <= count 1)
   (princ "Program Terminated Normally")
)



谢谢

标签: clisp

解决方案


一点反馈

(let ((a 0)
      (b 0)
      (count 0))
 (loop
   (= a b))      ; here the LOOP is already over.
                 ;  You have a closing parenthesis
                 ;   -> you need better formatting
   (princ"Enter Number: ")
   (defvar a(read))
   (format t "~% a = ~d" a)
   (setq count (1+ count))
(while
   (!= b(* a 2) || <= count 1)
   (princ "Program Terminated Normally")
)

一些改进的格式:

(let ((a 0)
      (b 0)
      (count 0))
  (loop
   (= a b))                  ; LOOP ends here, that's not a good idea
  (princ "Enter Number: ")
  (defvar a(read))           ; DEFVAR is the wrong construct,
                             ;   you want to SETQ an already defined variable
  (format t "~% a = ~d" a)
  (setq count (1+ count))
  (while                     ; WHILE does not exist as an operator
   (!= b(* a 2) || <= count 1)    ; This expression is not valid Lisp
   (princ "Program Terminated Normally")
   )

在真正编写这样的循环之前,您可能需要学习更多的 Lisp 运算符。您可能还想以交互方式使用 Lisp 并尝试一些事情,而不是尝试将代码编写到编辑器中并且永远不会从 Lisp 获得反馈......


推荐阅读