Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在OCaml中使用字符串格式从文件中读取数字列表_Ocaml - Fatal编程技术网

如何在OCaml中使用字符串格式从文件中读取数字列表

如何在OCaml中使用字符串格式从文件中读取数字列表,ocaml,Ocaml,我想以特定格式获取文件中的数字列表。但我没有得到任何类似于%s%d的数字列表格式 我的文件包含以下文本: [1;2] [2] 5 [45;37] [9] 33 [3] [2;4] 1000 我尝试了以下方法 value split_input str fmt = Scanf.sscanf str fmt (fun x y z -> (x,y,z)); value rec read_file chin acc fmt = try let line = input_line

我想以特定格式获取文件中的数字列表。但我没有得到任何类似于%s%d的数字列表格式

我的文件包含以下文本:

[1;2] [2] 5
[45;37] [9] 33
[3] [2;4] 1000
我尝试了以下方法

value split_input str fmt =  Scanf.sscanf str fmt (fun x y z -> (x,y,z));

value rec read_file chin acc fmt =
      try let line = input_line chin in
      let (a,b,c) = split_input line fmt in 
      let acc = List.append acc [(a,b,c)] in
            read_file chin acc fmt
      with 
      [ End_of_file -> do { close_in chin; acc}
      ];

value read_list = 
      let chin = open_in "filepath/filename" in
      read_file chin [] "%s %s %d";
问题在于最后指定的格式。我使用相同的代码从其他文件获取数据,其中数据的格式为string*string*int


为了重用相同的代码,我必须以字符串形式接收上述文本,然后根据我的要求进行拆分。我的问题是:整数列表是否有%s%d这样的格式,这样我就可以直接从文件中获取列表,而不是编写另一个代码将字符串转换为列表。

Scanf中没有列表的内置说明符。可以使用%r说明符将解析委托给自定义扫描程序,但Scanf并非真正用于解析复杂格式:

let int_list b = Scanf.bscanf b "[%s@]" (fun s ->
  List.map int_of_string @@ String.split_on_char ';' s
)
然后使用这个int_列表解析器,我们可以编写

let test = Scanf.sscanf "[1;2]@[3;4]" "%r@%r" int_list int_list (@)
获得

val测试:int list=[1;2;3;4]

正如所料。但同时,使用String.split_on_char进行拆分更容易。一般来说,解析复杂格式最好使用 regexp库、解析器组合器库或解析器生成器


注:您可能应该避免修改语法,因为它已被废弃。

问题是我对Ocaml是新手,我使用的是一个已经开发的代码,它是用修改后的代码编写的。如果我在Ocaml语法中添加新代码而不是修改后的代码,会有任何问题吗?