Common Lisp let 绑定
我有一个函数计算二项展开式,并带有可选参数来指定开始和结束项:
(defun comb-index (s k)
(let ((combinations nil))
(labels ((rec (s k offset entry)
(cond ((equal s k)
(push (reverse (loop
for i from 1 to s
do (push (1- (+ i offset)) entry)
finally (return entry)))
combinations))
((equal k 0)
(push (reverse entry) combinations))
(t (rec (1- s) (1- k) (1+ offset) (cons offset entry))
(rec (1- s) k (1+ offset) entry)))))
(rec s k 0 nil))
(nreverse combinations)))
(defun binomial (k &key (start 1) end)
(let ((b start)
(e (if (null end) k end)))
(labels ((rec (i)
(cond ((equal i e)
(comb-index k e))
(t
(append (comb-index k i) (rec (1+ i)))))))
(rec b))
)
)
当我编译并运行此代码时,它将产生以下运行时错误:
Unhandled memory fault at #x18.
[Condition of type SB-SYS:MEMORY-FAULT-ERROR]
这是由 e 引起的,但我不确定为什么。我可以通过为 'e' 分配 'k' 或 'end' 来避免这个问题,或者简单地使用 (when ... ) 将 'end' 设置为 'k'(如果它为零),但我不确定为什么这是行不通的。
I have a function calculate binomial expansion with optional parameters to specify the beginning and ending term:
(defun comb-index (s k)
(let ((combinations nil))
(labels ((rec (s k offset entry)
(cond ((equal s k)
(push (reverse (loop
for i from 1 to s
do (push (1- (+ i offset)) entry)
finally (return entry)))
combinations))
((equal k 0)
(push (reverse entry) combinations))
(t (rec (1- s) (1- k) (1+ offset) (cons offset entry))
(rec (1- s) k (1+ offset) entry)))))
(rec s k 0 nil))
(nreverse combinations)))
(defun binomial (k &key (start 1) end)
(let ((b start)
(e (if (null end) k end)))
(labels ((rec (i)
(cond ((equal i e)
(comb-index k e))
(t
(append (comb-index k i) (rec (1+ i)))))))
(rec b))
)
)
When I compile and run this code, it will yield the following run time error:
Unhandled memory fault at #x18.
[Condition of type SB-SYS:MEMORY-FAULT-ERROR]
This is caused by e, but I'm not sure why. I can avoid this problem by assigning 'e' with either 'k' or 'end', or simply using a (when ... ) to set 'end' to 'k' if it's nil, but I'm not sure why this doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来像内存溢出......
有没有想过你的代码的内存效率?
Looks like a memory overflow...
Ever thought about the memory efficiency of your code?
代码中的问题并不明显;这似乎是真正的溢出。有什么方法可以调整底层 Lisp 系统可用的内存吗?命令行标志什么的?
您是否可以选择使用像 Clojure 这样可以创建惰性序列的语言来实现此功能?您可能知道,这种类型的计算有可能产生非常大的结果。我似乎记得 Clojure/contrib 库之一中的某些内容就是执行此计算的。
The problem in the code isn't obvious; it just seems to be a real overflow. Is there any way you can adjust the memory available to the underlying Lisp system? Command line flags or something?
Do you have the option of implementing this in a language like Clojure that can create lazy sequences? As you are probably aware, this type of calculation has the potential to create extremely large results. I seem to recall something in one of the Clojure/contrib libraries that did just this calculation.