對於Euler項目Problem 8,我被告知需要解析一個1000位的數字。 這是一個蠻力的Lisp解決方案,它基本上每隔5個連續的數字進行一次,並將它們從開始到結束相乘,並返回循環結尾的最大數字。Common Lisp:「字符串中沒有非空白字符」
代碼:
(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))))))
編譯時沒有警告和upo運行它似乎運行得很好。例如,
CL_USER>(產品的-5N 1)=> 882
由於第一5個位數爲7,3,1,6和7
這似乎是正確的至於1000digits-str
,有人簡單地用defvar
編譯並與Emacs的longlines-show-hard-newlines
,我不認爲有在字符串中的任何空白字符,因爲這是SBCL抱怨,對不對?
使用EVAL是不好的。嘗試替換它。 – 2012-07-18 19:17:20