首页 > 解决方案 > 将源文件划分为多个模块的常规方法是什么?

问题描述

我有一个大约 380 行的源文件。它已经远远超过了难以阅读的地步,因为它只是一个s的大海define。我想把它分解,最好分成几个范围,而不仅仅是在每组相关定义之前插入评论。我也不想把它分成单独的源文件,因为我有几个非常相似的源文件:每个都是用不同的方式做同样事情的实验。如果我将每个文件分成多个源文件,我就会有一个我无法跟踪的扩散。

我认为moduleandmodule*表格是为此而设计的,但我还没有弄清楚它们是如何一起工作的。我尝试了各种组合,取得了不同程度的成功,但没有一个完全令人满意。我想我只是在这里问它是如何完成的。

源文件大致如下所示:

#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.
)

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

标签: modulescoperacket

解决方案


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

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

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

提示:在 Emacs 和 DrRacket 中,您可以通过点击 插入 60 个等号Escape 6 0 =。同样用于插入任何其他字符的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) ....)

推荐阅读