gpt4 book ai didi

common-lisp - 如何在普通的 lisp 中键入 DO 变量?

转载 作者:行者123 更新时间:2023-12-02 15:46:11 25 4
gpt4 key购买 nike

我知道你可以像这样声明函数参数类型

(defun add-integer (a b)
(declare (integer a b))
(the integer (+ a b)))

但是 DO 变量呢?例如,我想输入 passes:

(defun bench ()
(do ((end (+ (get-internal-real-time) (* 5 internal-time-units-per-second)))
(passes 0 (+ 1 passes)))
((> (get-internal-real-time) end)
passes)
(sieve 1000000)))

当我尝试使用 (declaim (optimize (speed 2) (safety 0))) 进行编译时,我得到了

; in: DEFUN BENCH
; (1+ PASSES)
;
; note: forced to do full call
; unable to do inline fixnum arithmetic (cost 2) because:
; The first argument is a UNSIGNED-BYTE, not a FIXNUM.
; The result is a (VALUES (INTEGER 1) &OPTIONAL), not a (VALUES FIXNUM
; &REST T).
; unable to do inline (unsigned-byte 64) arithmetic (cost 5) because:
; The first argument is a UNSIGNED-BYTE, not a (UNSIGNED-BYTE 64).
; The result is a (VALUES (INTEGER 1) &OPTIONAL), not a (VALUES
; (UNSIGNED-BYTE 64)
; &REST T).

我试过了

(defun bench ()
(declare (type (unsigned-byte 64) passes))
(do ((end (+ (get-internal-real-time) (* 5 internal-time-units-per-second)))
(passes 0 (+ 1 passes)))
((> (get-internal-real-time) end)
passes)
(sieve 1000000)))

但后来我明白了

;   Undefined variable:
; PASSES

我在 HyperSpec 的类型章节中找不到任何相关内容,例如(http://clhs.lisp.se/Body/04_bc.htm)。一个工作示例将非常有帮助!谢谢!

最佳答案

您将声明放在循环体的开头。

(defun bench ()
(do ((end (+ (get-internal-real-time) (* 5 internal-time-units-per-second)))
(passes 0 (+ 1 passes)))
((> (get-internal-real-time) end)
passes)
(declare (type (unsigned-byte 64) passes))
(sieve 1000000)))

这显示在 DO 的规范中:

do ({var | (var [init-form [step-form]])}*) (end-test-form result-form*) declaration* {tag | statement}*

(end-test-form result-form*)之后的declaration

关于common-lisp - 如何在普通的 lisp 中键入 DO 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74132629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com