1

我已经使用 ocamllex 和 ocamlyacc 编写了一个解释器,词法分析器和解析器工作正常,但目前它们只解析它收到的最后一个 .txt 参数,因为它们依次反对所有这些参数。例如,./interpret one.txt two.txt three.txt仅解析three.txt为与解析相反one.txt,然后two.txt再解析,three.txt这就是我想要的。因此,例如解析结果如下:

one.txt -> "1"
two.txt -> "2"
three.txt -> "3"

调用./interpret one.txt two.txt three.txt当前输出是:3但我希望它是123

这是我的主要课程,处理stdinstdout

open Lexer
open Parser
open Arg
open Printf

let toParse c = 
    try let lexbuf = Lexing.from_channel c in  
            parser_main lexer_main lexbuf 
    with Parsing.Parse_error -> failwith "Parse failure!" ;;


let argument = ref stdin in                                         
let prog p = argument := open_in p in
let usage = "./interpreter FILE" in
parse [] prog usage ; 
let parsed = toParse !argument in
let result = eval parsed in
let _ = parsed in
flush stdout;

谢谢你的时间

4

1 回答 1

1

这里没有足够的代码来提供帮助。

如果我假设输出是由 编写的eval,那么我只会看到一个对eval. 但是这里没有任何东西可以处理命令行中的文件名,所以很难说更多。

stdin如果您打算从文件中读取输入,那么据我所知,没有理由使用任何东西。

(我知道这是一个很小的问题,但这段代码并不构成一个类。其他语言对所有东西都使用类,但这是一个模块。)

更新

这是一个类似于 Unix cat 命令的模块;它从命令行一个接一个地写出所有文件的内容。

let cat () =
    for i = 1 to Array.length Sys.argv - 1 do
        let ic = open_in Sys.argv.(i) in
        let rec loop () =
            match input_line ic with
            | line -> output_string stdout (line ^ "\n"); loop ()
            | exception End_of_file -> ()
        in
        loop ();
        close_in ic
    done

let () = cat ()

这是编译和运行它时的样子。

$ ocamlc -o mycat mycat.ml
$ echo test line 1 > file1
$ echo test line 2 > file2
$ ./mycat file1 file2
test line 1
test line 2
于 2017-03-18T19:14:09.627 回答