为什么我不能在我的 lex 文件中使用模块?

Why can't I use module in my lex file?

这是我目前拥有的 mll 文件,运行良好。

{ type token = EOF | Word of string }

rule token = parse
    | eof { EOF }
    | ['a'-'z' 'A'-'Z']+ as word {Word(word)}
    | _ { token lexbuf }
{
    let lexbuf = Lexing.from_channel stdin in
    let wordlist = 
        let rec next l = 
            match token lexbuf with
                EOF -> l
            | Word(s) -> next (s::l)
        in next []
    in

    List.iter print_endline wordlist
}

我做 ocamllex a.mll 然后 ocamlc -o a a.ml。 运行 ./a < a.mll 将打印出存在于 mll 文件中的所有字符串,这正是我所期望的。

但是,如果我在 List.iter 调用之前添加 module StringMap = Map.Make(String),则会出现语法错误...
File "a.mll", line 17, characters 4-10: 其中第 17 行是带有 module 的行,4-10 是单词 module

我不明白为什么添加这一行会给我一个语法错误...如果我在顶层输入相同的代码,它就可以正常工作。

我假设 ocamllex 生成的代码最终在函数内部。您不能在函数内声明全局样式模块。

但是你可以像这样声明一个本地模块:

let module StringMap = Map.Make(String) in ...

示例:

# let fgm () =
      module StringMap = Map.Make(String)
      StringMap.cardinal StringMap.empty;;
Error: Syntax error
# let flm () =
      let module StringMap = Map.Make(String) in
      StringMap.cardinal StringMap.empty;;
val flm : unit -> int = <fun>
# flm ();;
- : int = 0