Racket模块导入基础知识

时间:2011-06-27 17:44:25

标签: module scheme racket

在使用Racket时,我正在尝试require另一个文件。我在同一个文件夹中有两个文件。它们是world.rktant.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  

我查找了有关导入和导出的文档,但我无法正确导入它。我觉得这很简单,我只是不了解语法。

我应该如何更改代码,以便在gen-grid中使用gen-cellant.rkt

1 个答案:

答案 0 :(得分:6)

您的代码看起来很好,当我测试它时没有问题。

但请注意两件事:

  1. 使用#lang racket(或#lang racket/base)开始您的代码,现在更好 了。这不仅成为惯例,它允许使用语言提供的任何语法扩展,而module表示您使用的是默认的sexpr。 (顺便说一句,它也更方便,因为你不需要使模块名称与文件名相同。)

  2. 在模块中使用load可能与您的想法有所不同。最好不要使用load,至少在你确切知道它在做什么之前。 (它与eval完全一样糟糕。)相反,你应该始终坚持require。当您了解更多内容时,您会发现有时dynamic-require也很有用,但暂时不要load