我完全理解CL的Loop宏有些麻烦。 这是Project Euler Nr的代码。 32:
(defun number-to-list (nr)
(map 'list #'digit-char-p (prin1-to-string nr)))
(defun nine-digits-p (multiplicand multiplier )
(= (length (equationlist multiplicand multiplier
(* multiplicand multiplier))) 9))
(defun equationlist (multiplicand multiplier product)
(append (number-to-list multiplicand) (number-to-list multiplier)
(number-to-list product)))
(defun pandigital (multiplicand multiplier)
(equal (sort (equationlist multiplicand multiplier
(* multiplicand multiplier)) #'<)
'(1 2 3 4 5 6 7 8 9)))
(defun pandigital-list ()
(loop
for i from 1 to 2000 collect
(loop for j from 2 to 2000
when (and (nine-digits-p i j) (pandigital i j)) collect (* i j))))
(defun euler-32 ()
(reduce #'+ (reduce #'union (pandigital-list))))
虽然这给了我正确的解决方案,但我的问题是功能“pandigital-list”。它不是仅收集pandigital数字,而是返回一个填充了“NIL”和少数正确数字的列表。
如何更改此功能只返回我感兴趣的数字?
答案 0 :(得分:3)
问题是,只要内部loop
没有收集任何其他内容,它就会返回nil
。 (记住:在Common Lisp中,一切都有价值。)
一种解决方案是重新定义pandigital-list
,如下所示:
(defun pandigital-list ()
(loop for i from 1 to 2000
for sublist = (loop for j from 2 to 2000
when (and (nine-digits-p i j)
(pandigital i j))
collect (* i j))
when sublist collect sublist))