📜  LISP-循环

📅  最后修改于: 2020-11-03 07:09:40             🧑  作者: Mango


在某些情况下,您需要执行一段代码次数。循环语句使我们可以多次执行一个语句或一组语句,以下是大多数编程语言中循环语句的一般形式。

循环

LISP提供以下类型的构造来处理循环需求。单击以下链接以查看其详细信息。

Sr.No. Construct & Description
1 loop

The loop construct is the simplest form of iteration provided by LISP. In its simplest form, it allows you to execute some statement(s) repeatedly until it finds a return statement.

2 loop for

The loop for construct allows you to implement a for-loop like iteration as most common in other languages.

3 do

The do construct is also used for performing iteration using LISP. It provides a structured form of iteration.

4 dotimes

The dotimes construct allows looping for some fixed number of iterations.

5 dolist

The dolist construct allows iteration through each element of a list.

优雅地退出街区

返回源可让您从任何嵌套块中正常退出,以防出现任何错误。

函数使您可以创建包含零个或多个语句的主体的命名块。语法是-

(block block-name(
...
...
))

return-from函数采用一个块名和一个可选的(默认值为nil)返回值。

以下示例演示了这一点-

创建一个名为main.lisp的新源代码文件,并在其中键入以下代码-

(defun demo-function (flag)
   (print 'entering-outer-block)
   
   (block outer-block
      (print 'entering-inner-block)
      (print (block inner-block

         (if flag
            (return-from outer-block 3)
            (return-from inner-block 5)
         )

         (print 'This-wil--not-be-printed))
      )

      (print 'left-inner-block)
      (print 'leaving-outer-block)
   t)
)
(demo-function t)
(terpri)
(demo-function nil)

当您单击执行按钮或键入Ctrl + E时,LISP立即执行它,返回的结果是-

ENTERING-OUTER-BLOCK 
ENTERING-INNER-BLOCK 

ENTERING-OUTER-BLOCK 
ENTERING-INNER-BLOCK 
5 
LEFT-INNER-BLOCK 
LEAVING-OUTER-BLOCK