如何编写同时兼容Chez Scheme与Chicken Scheme的程序?
兼容Chez Scheme与Chicken Scheme的程序编写方案
我尝试编写一个同时兼容Chez Scheme与Chicken Scheme的程序,先从最简版本测试:
测试1:仅含核心输出的最简版本
代码文件hello.ss:
(display "hello, world\n")
运行结果:
- Chicken Scheme正常执行:
(c1) R:\>csc hello.ss (c1) R:\>hello hello, world
- Chez Scheme报错:
(c1) R:\>"C:\Program Files\Chez Scheme 9.5.8\bin\a6nt\scheme.exe" --program hello.ss Exception: invalid top-level program import subform (display "hello, world\n") at line 1, char 1 of hello.ss
测试2:添加RNRS导入适配Chez
代码文件hello2.ss:
(import (rnrs)) (display "hello, world\n")
运行结果:
- Chez Scheme正常执行:
(c1) R:\>"C:\Program Files\Chez Scheme 9.5.8\bin\a6nt\scheme.exe" --program hello2.ss hello, world
- Chicken Scheme报错:
(c1) R:\>csc hello2.ss Syntax error (import): cannot import from undefined module rnrs Expansion history: <syntax> (##core#begin (import (rnrs))) <syntax> (import (rnrs)) <-- Error: shell command terminated with non-zero exit status 70: ""c:/chicken/bin/chicken.exe" "hello2.ss" -output-file "hello2.c""
兼容两种实现的解决方案
利用Scheme标准的cond-expand条件扩展机制,针对不同实现做差异化处理:
;; 针对Chez Scheme导入RNRS库,Chicken Scheme默认已加载核心函数 (cond-expand (chez (import (rnrs))) (chicken #t) ; Chicken无需额外导入核心库,空操作占位 (else #t)) ; 兼容其他Scheme实现的占位 (display "hello, world\n")
核心逻辑说明:
cond-expand会根据当前Scheme实现的内置标识符,执行对应分支的代码:Chez Scheme定义了chez标识符,Chicken Scheme定义了chicken标识符- Chicken Scheme的核心函数(如
display)默认在全局环境中可用,无需额外导入模块 - Chez Scheme以
--program模式运行时,必须显式导入RNRS库才能使用标准核心函数
验证运行
将上述代码保存为hello-compat.ss,分别测试:
- Chicken Scheme:
(c1) R:\>csc hello-compat.ss (c1) R:\>hello-compat hello, world
- Chez Scheme:
(c1) R:\>"C:\Program Files\Chez Scheme 9.5.8\bin\a6nt\scheme.exe" --program hello-compat.ss hello, world
内容的提问来源于stack exchange,提问作者rwallace
相关产品推荐
相关产品推荐

