如何在 Scheme 中导入模块(尤其是诡计)?
如何创建模块并将其导入方案中的另一个脚本中?导入模块时应该如何编译脚本,必须传递的命令行参数是什么?如果模块在另一个目录中,如何导入?
让我们创建一个模块test_module.scm,其中包含以下代码,其位置为/some/dir,
(define-module (test_module)
#: export (square
cube))
(define (square a)
(* a a))
(define (cube a)
(* a a a))
在这里,我们使用以下语法创建了一个模块:
(define-module (name-of-the-module)
#: export (function1-to-be-exported
function2-to-be-exported))
;; rest of the code goes here for example: function1-to-be-exported
现在让我们创建一个脚本来导入我们创建的名为 use_module.scm 的模块,其中包含此代码,位于当前目录中。
(use-modules (test_module))
(format #t "~a\n" (square 12))
在这里,我们使用了使用语法的模块:
(use-modules (name-of-the-module))
;; now all the functions that were exported from the
;; module will be available here for our use
现在让我们进入编译部分,我们必须将 GUILE_LOAD_PATH 设置为位置/some/dir然后编译脚本。
现在让我们假设 test_module.scm 和 use_module.scm 都在同一个目录中,然后这样做:
$ GUILE_LOAD_PATH=. guile use_module.scm
但如果模块存在于/some/dir中,通常会这样做:
$ GUILE_LOAD_PATH=/some/dir guile code.scm
ps 更简单的方法是编写脚本,使用add-to-load-path告诉 guile 模块的位置。现在我们可以编译而不用担心环境变量了。
(add-to-load-path "/some/dir")
(use-modules (name-of-the-module))
;; rest of the code