将源文件分为几个模块的常规方法是什么?

时间:2018-09-26 00:43:02

标签: module scope racket

我有一个大约380行长的源文件。它已经远远超过了难以阅读的地步,因为它只是define的一大堆。我想将其分解为多个范围,而不仅仅是在每组相关定义之前插入注释。我也不想将其分成单独的源文件,因为我有几个非常相似的源文件:每个源文件都是一个以不同的方式做相同事情的实验。如果我将每个文件分解成多个源文件,那我将无法追踪。

我认为modulemodule*表单是为此而设计的,但是我还没有弄清楚它们是如何协同工作的。我尝试过各种组合,但成功的程度各不相同,没有一个完全令人满意。我以为我只想问一下它是怎么做到的。

源文件大致如下:

#lang debug at-exp racket

(require rackunit data/collection racket/dict racket/generic racket/pretty
         racket/hash describe "graph.rkt")  ; <--- same requires needed in every scope
(provide make-slipnet run-slipnet spread-activation ...)

;; defines for making a 'slipnet' graph ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define ...)
(define ...)
(module+ test
  ...)
(define ...)
(module+ test
  ...)
...
(define (make-slipnet ...) ...) ;The rest of the file only needs these
(define (run-slipnet ...) ...)  ;two functions from this section.

;; defines for doing spreading activation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define ...)
(define ...)
(module+ test
  ...)
...
(define (spread-activation ...) ...) ;The rest of the file only needs this
                                     ;function from this section
;; Etc.

(module+ main
  ;generate some human-readable output here, calling make-slipnet,
  ;run-slipnet, spread-activation, functions from "graph.rkt", etc.
)

您如何将这些功能划分为自然的组?

1 个答案:

答案 0 :(得分:1)

使用子模块进行语义组织。使用注释进行视觉组织。

子代码仅在某些模式下运行时才有用(例如,test子模块用于测试,main子模块用于程序/命令等)。当您在编译时(在宏转换器内)和运行时都需要相同的辅助函数时,它们也很有用;您可以在子模块中一次定义它,并在多个阶段要求该子模块。

但是,否则,只需使用注释和空格即可。我目前的偏好是用60个等号的行(双行)分隔主要部分,并用40个连字符的行分隔次要部分。有时,我会在该行下方放置一个节标题(如果我能想到一个简洁的标签)。

提示:在Emacs和DrRacket中,您都可以通过点击Escape 6 0 =来插入60个等号。同样,用于插入任何其他字符的 n 个副本。

示例:

;; ============================================================
;; Data definitions

;; A Vertex is a Symbol.

;; A Graph is (graph (hashof Vertex (Listof Vertex))).
(struct graph (out-edges))

;; ============================================================
;; Graph algorithms

;; ----------------------------------------
;; Paths

;; find-path : Graph Vertex Vertex -> (U #f (Listof Vertex))
(define (find-path g from to) ....)

;; ----------------------------------------
;; Strongly-connected components (SCCs)

;; vertex->scc : Graph Vertex -> (Listof Vertex)
(define (vertex->scc g vertex) ....)

;; ============================================================
;; External forms

;; read-graph : InputPort -> Graph
(define (read-graph in) ....)

;; write-graph : Graph OutputPort -> Void
(define (write-graph g out) ....)