我正在尝试 require
使用 Racket 时,一个文件在另一个文件中。我在同一个文件夹中有两个文件。他们是 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))))))
现在,我可以输入
(require "ant.rkt")
在 REPL 中,然后当我输入 (gen-cell 'none 'white)
我得到错误:reference to undefined identifier: gen-cell
我查看了有关导入和导出的文档,但无法正确导入。我觉得这很简单,我只是不了解语法。
我应该如何更改我的代码以便我可以使用
gen-grid
和 gen-cell
在 ant.rkt
?
最佳答案
你的代码看起来不错,当我测试它时没有问题。
但请注意两点:
#lang racket
开始你的代码。 (或 #lang racket/base
)。这不仅成为惯例,它还允许使用该语言为您提供的任何句法扩展,而 module
表示您使用的是默认的 sexpr。 (顺便说一句,它也更方便,因为您不需要使模块名称与文件名相同。)load
with modules 所做的可能与您认为的有所不同。最好避免使用 load
,至少在您确切知道它在做什么之前。 (它与 eval
一样糟糕。)相反,您应该始终坚持使用 require
.当您了解更多时,您有时会看到 dynamic-require
也很有用,但请保留 load
暂时出去。 关于module - Racket 模块导入基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6496773/