You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CM文件编译SML代码时HashTable结构未绑定错误求助

解决SML/NJ中HashTable未绑定的CM编译问题

问题场景

使用build.cm编译SML项目时,symbol_table.sml中引用SML/NJ的HashTable结构,触发以下编译错误:

Standard ML of New Jersey v110.79 [built: Sat Oct 26 12:27:04 2019]
- CM.make "build.cm" ;
[autoloading done]
[compiling (build.cm):symbol_table.sml]
symbol_table.sml:6.43-6.63 Error: unbound structure: HashTable in path HashTable.hash_table
symbol_table.sml:14.3-14.17 Error: unbound structure: HashTable
val it = false : bool

相关代码片段:

symbol_table.sml

signature SYMTABLE =
sig
val table : (string,Rational.rational) HashTable.hash_table ;
val add_entry : string * Rational.rational -> unit ;
val lookup_entry : string -> Rational.rational
end ;

structure SymTable : SYMTABLE  =
struct
open Rational ; 
open HashTable ; 
exception lookup_error

val hash_fn : string->word = HashString.hashString
fun cmp_fn(x : string ,y : string) = (x = y)
val init_sz : int = 101
val table: (string,rational) hash_table = mkTable (hash_fn, cmp_fn)(init_sz, lookup_error)
fun add_entry(key, value) = insert table (key,value) ;
fun lookup_entry(key) = lookup table key ;
end ;

原build.cm

Library 
    structure compile
is 
    $/basis.cm 
    $/ml-yacc-lib.cm 
    $/smlnj-lib.cm
    $smlnj/compiler/compiler.cm
    bigint.sml
    rational.sml
    symbol_table.sml 
    calc.lex 
    calc.yacc: MLYacc
    glue.sml 
    compiler.sml

问题原因

HashTable结构不属于SML基础库($/basis.cm),而是位于SML/NJ标准库的smlnj-lib/hashtbl.cm子库中。虽然$/smlnj-lib.cm是顶层库,但它不会自动加载所有子库,必须显式声明依赖才能让CM编译器找到HashTable。

解决方案

在build.cm的依赖列表中添加$smlnj-lib/hashtbl.cm,修改后的文件如下:

修改后的build.cm

Library 
    structure compile
is 
    $/basis.cm 
    $/ml-yacc-lib.cm 
    $/smlnj-lib.cm
    $smlnj-lib/hashtbl.cm  (* 新增HashTable所在的子库依赖 *)
    $smlnj/compiler/compiler.cm
    bigint.sml
    rational.sml
    symbol_table.sml 
    calc.lex 
    calc.yacc: MLYacc
    glue.sml 
    compiler.sml

额外优化建议(可选)

为了避免全局open HashTable带来的命名冲突,可以改为局部引用或限定式调用:

(* 替代open HashTable的写法 *)
val table: (string,rational) HashTable.hash_table = HashTable.mkTable (hash_fn, cmp_fn)(init_sz, lookup_error)
fun add_entry(key, value) = HashTable.insert table (key,value) ;
fun lookup_entry(key) = HashTable.lookup table key ;

内容的提问来源于stack exchange,提问作者Aaveg jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:35:27