对于欧拉计划 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 提示的,对吧?
最佳答案
I don't think there are any white-space characters in the string, because that's what SBCL is complaining about, right?
错误消息不是提示存在 空白,而是提示不存在 非-空白。但这实际上有点误导:消息应该说的是要解析的特定子字符串中没有非空白。这是因为您跑到了字符串的末尾,所以我们正在解析一个零长度的子字符串。
此外,product-of-5n
的定义不正确。 (product-of-5n 1)
返回前五位数字的乘积只是偶然的。字符串从 0
开始索引,因此 (product-of-5n 1)
以 second 字符开始;并且该函数从n + 0 迭代到n + 5,总共六个字符;所以 (product-of-5n 1)
返回 3 × 1 × 6 × 7 × 1 × 7,恰好与 7 × 3 × 1 × 6 × 7 × 1 相同。
关于lisp - 普通口齿不清 : "no non-white-space characters in string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11548131/