我在 OS X 上使用 Guile 1.8.8
解释器练习 Scheme。我注意到了一些有趣的事情。
这是一个 expt
函数,它基本上执行幂运算 expt(b,n) = b^n
:
(define (square x) (* x x))
(define (even? x) (= (remainder x 2) 0))
(define (expt b n)
(cond ((= n 0) 1)
((even? n) (square (expt b (/ n 2))))
(else (* b (expt b (- n 1))))
))
如果我用一些输入尝试它
> (expt 2 10)
1024
> (expt 2 63)
9223372036854775808
这里来了个奇怪的部分:
> (expt 2 64)
0
更奇怪的是,直到n=488
时它仍保持为0
:
> (expt 2 487)
0
> (expt 2 488)
79916762888089401123.....
> (expt 2 1000)
1071508607186267320948425049060....
> (expt 2 10000)
0
当我使用repl.it在线编译器运行这段代码时,它按预期工作。那么Guile到底出了什么问题?
(注意:在某些方言中,remainder
函数被称为mod
。)
expt
重命名为my-expt
。这样可以排除问题是您的expt
还是内置的expt
的任何混淆。 - soegaard