【发布时间】:2012-07-18 18:38:10
【问题描述】:
对于 Project Euler Problem 8,我被告知要解析一个 1000 位数字。 这是一个蛮力的 Lisp 解决方案,它基本上每 5 个连续的数字进行一次,并从头到尾将它们相乘,并在循环结束时返回最大的一个。
代码:
(defun pep8 ()
(labels ((product-of-5n (n)
(eval (append '(*)
(loop for x from n to (+ n 5)
collect (parse-integer
1000digits-str :start x :end (+ x 1)))))))
(let ((largestproduct 0))
(do ((currentdigit 0 (1+ currentdigit)))
((> currentdigit (- (length 1000digits-str) 6)) (return largestproduct))
(when (> (product-of-5n currentdigit) largestproduct)
(setf largestproduct (product-of-5n currentdigit)))))))
它编译时没有任何警告,但在运行时我得到:
no non-whitespace characters in string "73167176531330624919225119674426574742355349194934...".
[Condition of type SB-INT:SIMPLE-PARSE-ERROR]
我检查了本地函数 product-of-5n 是否正在工作,方法是再次将其编写为全局函数:
(defun product-of-5n (n)
(eval (append '(*)
(loop for x from n to (+ n 5)
collect (parse-integer
1000digits-str :start x :end (+ x 1))))))
编译时没有警告,运行时似乎运行良好。例如,
CL_USER> (product-of-5n 1) => 882
这似乎是正确的,因为前五个数字是 7、3、1、6 和 7。
至于1000digits-str,它只是用defvar编译的,而用Emacs的longlines-show-hard-newlines,我不认为字符串中有任何空白字符,因为这就是 SBCL 所抱怨的,对吧?
【问题讨论】:
-
使用 EVAL 是不好的。尝试替换它。
标签: lisp common-lisp sbcl