Search code examples
ocamlocamllex

OCaml Syntax Error in Parser


Can someone help me explain why I have a syntax error at this line: let wordMap = StringMap.empty? This is contained in an .mll file. The module StringMap is defined above.

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 []

    let wordMap = StringMap.empty in 
        let wcList  = StringMap.fold (fun word count l -> (string_of_int count ^ " " ^ word) :: l) wordMap [] in 

        List.iter print_endline wcList;;

I know it prints nothing, this is just for testing.


Solution

  • A declaration like:

    let v = expr
    

    can only appear at the outermost level of a module. It's the way to declare the global names of the module.

    But you have such a declaration (of wordlist) inside an expression:

    let lexbuf = ... in
    let wordlist = ...
    

    In all places other than the outer level of a module, let must be followed by in. This is the way to declare a local variable (in any expression).

    let v = expr1 in expr2
    

    I'm not clear which of your names you want to be global. But one way to solve the problem would be to remove the first in. Then you would have three global names, lexbuf, wordlist, and wordMap.

    Another way would be to add in after the definition of wordlist. Then you would have no global names.