我在使用Racket时正试图在另一个文件中使用 require
. 我在同一个文件夹中有两个文件 . 它们是 world.rkt
和 ant.rkt
.
world.rkt
:
(module world racket
(provide gen-grid gen-cell)
(define (gen-cell item fill)
(cons item fill))
(define (gen-grid x y fill)
(begin
(define (gen-row x fill)
(cond ((> x 0) (cons (gen-cell (quote none) fill)
(gen-row (- x 1) fill)))
((<= x 0) (quote ()) )))
(cond ((> y 0) (cons (gen-row x fill)
(gen-grid x (- y 1) fill)))
((<= y 0) (quote ()) )))))
ant.rkt
:
(module ant racket
(require "world.rkt")
(define (insert-ant grid x y)
(cond ((> y 0) (insert-ant (cdr grid) x (- y 1)))
((< y 0) 'Error)
((= y 0) (begin
(define y-line (car grid))
(define (get-x line x)
(cond ((> x 0) (get-x (cdr line) (- x 1)))
((< x 0) 'Error)
(= x 0) (gen-cell 'ant (cdr (car line))) ))
(get-x y-line x))))))
现在,我可以在REPL中输入 (require "ant.rkt")
,然后当我输入 (gen-cell 'none 'white)
时出现错误:
reference to undefined identifier: gen-cell
我已查阅有关导入和导出的文档,但我无法正确导入它 . 我觉得这很简单,我只是不了解语法 .
我应该如何更改我的代码,以便在 ant.rkt
中使用 gen-grid
和 gen-cell
?
1 回答
你的代码看起来很好,当我测试它时没有问题 .
但请注意两件事:
现在用
#lang racket
(或#lang racket/base
)启动代码要好得多 . 这不仅成为惯例,它允许使用语言提供的任何语法扩展,而module
意味着您也更方便,因为您不需要使模块名称与文件名相同 . )在模块中使用
load
可能与您的想法有所不同 . 最好避免使用load
,至少在你确切知道它在做什么之前 . (它与eval
一样糟糕 . )相反,你应该始终坚持require
. 当你学到更多东西时,你可以看到有时dynamic-require
也很有用,但现在就保持load
.