图书信息

首页 | 登录 | 注册 | 读书笔记游览

《Common Lisp代码学习》

关键词: 编程 lisp
作者: LispSu
出版社:
索引号: T.2024LISPSU001

原文摘录(6):

(defun start-of-file (file max-chars)
  (with-open-file (in file
                      :external-format :utf8)
    (let* ((length (min (file-length in) max-chars))
           (text (make-string length))
           (read (read-sequence text in)))
      (if (< read length)
          (subseq text 0 read)
          text))))
(defun fast-expt (a n)
  "快速迭代求指数"
  (labels ((iter (b counter product)
		 (cond ((zerop counter) product)
		       ((even? counter)
			(iter (* b b) (/ counter 2) product))
		       (t 
			(iter b (1- counter) (* b product))))))
    (iter a n 1)))
(defun my-expt (a n)
  "迭代求指数"
  (labels ((expt-iter (b counter product)
	     (if (zerop counter)
		 product
		 (expt-iter b (1- counter) (* b product)))))
    (expt-iter a n 1)))
(defun factorial (n)
  "迭代方法求阶乘"
  (labels ((fac-iter (product counter)
	     (if (zerop counter)
		 product
		 (fac-iter (* product counter) (1- counter)))))
    (fac-iter 1  n)))
(defun generate-random-string (length)                        
"生成一个指定长度的随机字符串,包含字母和数字。"
     (let ((charset "abcdefghijklmnopqrstuvwxyz0123456789"))      
       (coerce (loop repeat length collect
                     (char charset 
                           (random (length charset))))  
             'string)))
(defun euclid (m n)
  "欧几里得算法求两个正整数的最大公因子。"
  (labels ((algor (a b)
	       (if (zerop (mod a b))
		   b
		   (algor b (mod a b)))))
    (if (> m n)
	(algor m n)
	(algor n m))))