在Scribble中如何获取当前处理文件的路径以简化文件引用?
在Scribble中使用同目录相对路径引用非Racket文件
你可以通过获取当前.scrbl文件的路径,构建同目录下目标文件的路径,实现和@include-section一致的相对路径效果,具体操作如下:
- 先导入必要的工具库:
(require racket/path)
- 获取当前
.scrbl文件所在的目录:
;; 获取当前assignment.scrbl的完整文件路径 (define current-file (syntax-source #'here)) ;; 提取出文件所在的目录路径 (define current-dir (path-only current-file))
- 拼接目标文件的完整路径:
;; 生成同目录下template.EXT的路径 (define template-path (build-path current-dir "template.EXT"))
之后读取文件时直接用template-path即可,不用再写hw/hwN/template.EXT这类根相对路径。
如果需要多次使用,还可以封装成简易宏简化代码:
(require racket/path syntax/parse/define) (define-simple-macro (local-path filename:string) (build-path (path-only (syntax-source #'filename)) filename))
使用时直接调用宏生成路径:
(define template-path (local-path "template.EXT"))
这种方式的核心是利用syntax-source #'here获取当前代码所在的源文件路径,再通过path-only提取目录,最后用build-path安全拼接文件名——和@include-section的路径查找逻辑完全一致,后续调整目录结构时,只要assignment.scrbl和template.EXT保持同目录,代码就不用做任何修改。
内容的提问来源于stack exchange,提问作者Daniel Patterson
相关产品推荐
相关产品推荐

