gpt4 book ai didi

racket - 我如何在 Dr Racket 中取消定义?

转载 作者:行者123 更新时间:2023-12-04 18:20:29 26 4
gpt4 key购买 nike

在构建某些功能时,我可能会犯一些错误。发生这种情况时,我单击运行并必须重新输入所有以前的定义和新的尝试。

有什么方法可以“取消定义”之前的 (define (func args ...) body) 并继续下去吗?

最佳答案

首先,行为是设计使然。变量不能在模块外改变。这给了优化器一个机会,除其他外事物,内联各种事物。参见 http://docs.racket-lang.org/guide/module-set.html以获得详细的解释。

如果你需要修改模块内部的东西,执行此操作的标准方法是使用参数。

这是一个滥用参数的快速 hack(我的意思是 hack)使重新定义成为可能。

要声明一个函数是可重定义的,使用redefineable。在此示例中,函数 foo 被声明为可重新定义。

#lang racket

(define-for-syntax (make-current-name stx id)
(datum->syntax
stx (string->symbol
(format "current-~a" (syntax-e id)))))

(define-syntax (redefine stx)
(syntax-case stx ()
[(_ (name arg ...) body ...)
(with-syntax ([current-name (make-current-name stx #'name)])
#'(current-name (lambda (arg ...) body ...)))]))

(define-syntax (redefineable stx)
(syntax-case stx ()
[(_ name)
(with-syntax ([current-name (make-current-name stx #'name)])
#'(begin
(define current-name (make-parameter (λ x (error 'undefined))))
(define (name . xs)
(apply (current-name) xs))))]))

(redefineable foo)

(redefine (foo x) (+ x 1))

现在运行程序,在交互窗口中,我们现在可以进行如下操作:

Welcome to DrRacket, version 5.3.0.6--2012-05-11(9401a53/a) [3m].
Language: racket.
> (foo 41)
42
> (redefine (foo x y) (* x y))
> (foo 2 3)
6

关于racket - 我如何在 Dr Racket 中取消定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10789160/

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