嗨,我是通用Lisp的新手,我找不到任何与我当前问题相关的教程,我对Java有很好的了解,我试着把简单的程序从Java转换成Common作为一种练习,而我不能做的一件特别的事情是,时间循环,我怎么做呢?它总是导致未定义的函数。
TL;博士
如何在普通的LISP中使用像这样的Java中的某些条件执行while循环:
while(UserIn > 0)
{
LastD = UserIn % 10;
Sum = Sum + LastD;
Product = Product * LastD;
UserIn = UserIn / 10;
}
if (Sum == Product)
{
System.out.println("\nGiven number is a Spy number");
}
else
{
System.out.println("\nGiven number is not a Spy number");
}我在普通LISP中的尝试如下
(while (> userIn 0)
(setq LastD(mod 10 UserIn))
(setq Product(* LastD Product))
(setq Sum(+ LastD Sum))
(setq UserIn(/ UserIn 10)))
(terpri)
(if (= a b)
(format t "is a spy number")
(format t "is not a spy number"))
)
(Spynumber)它不停地说:调试器调用了一个未定义的函数,谢谢!
发布于 2020-12-15 13:42:12
普通的Lisp没有while表单,但是它有一个功能强大得多的loop宏,其中包含您想要的while关键字:
(loop while ... do ...)发布于 2020-12-15 15:00:02
正如其他人所说的,您可以使用loop来实现这一点,这将是一种惯用的方法。
但是Lisp是可编程编程语言:如果您想要while,可以使用while。
(defmacro while (test &body decls/tags/forms)
`(do () ((not ,test) (values))
,@decls/tags/forms))而现在
> (let ((i 0))
(while (< i 10)
(print i)
(incf i)))
0
1
2
3
4
5
6
7
8
9
> 发布于 2020-12-18 01:11:22
使用do,您可以并行地循环和分配变量,语法如下:
(do ((<var1> <var1-initial-value> <var1-step>)
(<var2> <var2-initial-value> <var2-step>)
...)
((<exit-condition>)
(<final-statement1>)
(<final-statement2>)
...)
(<action1-during-loop>)
(<action2-during-loop>)
...)因此,对于您的代码,或多或少:
(let* ((UserIn (read))
(UI UserIn))
(do* ((LastD (rem UserIn 10) (rem UserIn 10))
(Sum 0 (+ Sum LastD))
(Product 1 (* Product LastD))
(UserIn UserIn (truncate UserIn 10)))
((<= UserIn 0)
(format t "~&LastD: ~f, Sum: ~f, Product: ~f, UserIn: ~f"
LastD Sum Product UserIn)
(if (= Sum Product)
(format t "~&~A is Spy number" UI)
(format t "~&~A is Not Spy number" UI)))
(format t "~&LastD: ~f, Sum: ~f, Product: ~f, UserIn: ~f"
LastD Sum Product UserIn)))
> LastD: 4.0, Sum: 0.0, Product: 1.0, UserIn: 1124.0
> LastD: 4.0, Sum: 4.0, Product: 4.0, UserIn: 112.0
> LastD: 2.0, Sum: 6.0, Product: 8.0, UserIn: 11.0
> LastD: 1.0, Sum: 7.0, Product: 8.0, UserIn: 1.0
> LastD: 1.0, Sum: 8.0, Product: 8.0, UserIn: 0.0
> 1124 is Spy number
> LastD: 2.0, Sum: 0.0, Product: 1.0, UserIn: 12.0
> LastD: 2.0, Sum: 2.0, Product: 2.0, UserIn: 1.0
> LastD: 1.0, Sum: 3.0, Product: 2.0, UserIn: 0.0
> 12 is Not Spy number对于一些代码片段,您可以访问http://rosettacode.org/wiki/Rosetta_Code。
https://stackoverflow.com/questions/65304891
复制相似问题