Lisp学习笔记1——打印素数

(defun print-prime-number (&key (begin 2) (end 100))
	   (format t "prime number between ~d and ~d: " begin end)
	   (format t "~{~d~t~}"
		   (loop for i from begin to end
			when (loop for j from 2 to (sqrt i) never (= 0 (mod i j))) collect i)))


调用示例1: (使用默认实参)
(print-prime-number)
输出:
prime number between 2 and 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 
NIL
调用2: (指定 begin 和 end)
(print-prime-number :begin 2 :end 200)
输出:
prime number between 2 and 200: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 
NIL

简化版,返回一个列表:
(defun prime-numbers (&key (begin 2) (end 100))
	   (loop for i from begin to end when (loop for j from 2 to (sqrt i) never (= 0 (mod i j))) collect i))
CL-USER> (prime-numbers :begin 2 :end 200)
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199)

知识点:

1. 关键字形参的使用, &key 后面的参数调用时要写成 :begin、:end 以指定是给哪个关键字的值. 还可写成 (begin 2 begin-p),其中 begin-p 指示了是否传递进来了begin的值.

2. loop的使用. loop var from i to j when bool-form collect var. 收集(i, j) 之间满足 bool-form 条件的值,循环变量为var.

3. (sqrt i) 相当于c语言的 sqrt(i).

你可能感兴趣的:(c,语言,lisp)