使用Common Lisp进行排序时出现意外的列表重复 [英] Unexpected List Duplication using Sort with Common Lisp

查看:107
本文介绍了使用Common Lisp进行排序时出现意外的列表重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案是在第一个(let ...)表单中将'(1)替换为(列表1).这是因为我试图修改文字数据.谢谢您的帮助! (我会放弃投票,但显然您需要15个声誉...)

The solution is to replace the '(1) with (list 1) in the first (let...) form. This is because I was trying to modify literal data. Thanks for the help! (I would give upvotes, but apparently you need 15 reputation...)

这是我在此网站上的第一篇文章.

This is my first post on this site.

我今天解决了一些 Project Euler 问题,我遇到了一些意外的列表排序行为(嗯,至少对我来说) )在Common Lisp中:

I was solving some Project Euler problems today and I came across some unexpected list sorting behavior (well, at least to me) in Common Lisp:

我有一个函数,可以找到数字x的所有适当除数:

I have a function that finds all of the proper divisors of a number x:

(defun divisors (x)
    "Finds all of the proper divisors of x."
    (let ((sq (sqrt x)) (divs '(1)))
        (when (integerp sq) (push sq divs))
        (loop for i from 2 to (1- (floor sq)) do
        (let ((div (/ x i)))
            (when (integerp div)
                (push i divs)
                (push div divs))))
    divs))

此功能很好用.例如:

(divisors 100)
==> (20 5 25 4 50 2 10 1)

每当我尝试对结果列表进行排序时,都会出现问题:

The problem arises whenever I try to sort the resulting list:

(sort (divisors 100) #'<)
==> (1 2 4 5 10 20 25 50)

嗯,效果很好.但是,当我再次调用除数时会发生什么?

Well, that worked fine. But what happens when I call divisors again?

(divisors 100)
==> (20 5 25 4 50 2 10 1 2 4 5 10 20 25 50)

什么?也许如果我尝试其他号码...

What? Maybe if I try a different number...

(divisors 33)
==> (11 3 1 2 4 5 10 20 25 50)

我对结果列表进行排序后,先前查询的除数将保持不变.如果我重新编译该函数,则不会出错,直到再次对结果列表进行排序为止.我假设我已经弄乱了函数定义中的某个地方,但是我对Lisp还是很陌生,并且找不到错误.嵌套(let ...)表单可能有问题吗?

The divisors from previous queries are persistent after I sort the resulting list. If I recompile the function, I get no errors until I sort the resulting list again. I am assuming I have messed up somewhere in the function definition, but I am pretty new to Lisp and I cannot find the error. Could it be a problem with the nested (let...) forms?

提前谢谢!

推荐答案

常见问题.

您已修改文字数据.您需要获取新数据.使用功能LIST或功能进行复制.

You've modified literal data. You need to cons up new data. Use the function LIST or the function to make a copy.

这篇关于使用Common Lisp进行排序时出现意外的列表重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆