【问题标题】:OCaml - Reading from file and splitting on characterOCaml - 从文件中读取并拆分字符
【发布时间】:2018-11-09 00:24:20
【问题描述】:

我正在尝试从 OCaml 中的文件中读取数据,并将每一行分成由空格分隔的字符串列表,然后将该列表附加到累积列表中。我收到的错误是:

File "bin/scanner.ml", line 17, characters 25-42: Error: This expression has type string list but an expression was expected of type unit

我的整个程序(scanner.ml)是:

  1 let tokens = [];;
  2 
  3 let split_spaces line =
  4     (String.split_on_char ' ' line) @ tokens;
  5     ;;
  6 
  7 (* Read input from an external file *)
  8 let line_stream_of_channel channel =
  9     Stream.from
 10         (fun _ ->
 11             try Some (input_line channel) with End_of_file -> None)
 12     ;;
 13 
 14 let in_channel = open_in "./input_files/test.c" in
 15     try
 16         Stream.iter
 17             (fun line -> split_spaces line)
 18         (line_stream_of_channel in_channel);
 19         close_in in_channel
 20     with e ->
 21         close_in in_channel;
 22         raise e
 23     ;;

我想我理解错误是 split_space 返回一个字符串列表,而第 17 行中的匿名函数需要一个函数返回类型单元。我坚持的是如何修改 split_spaces 使其返回类型为单位。

【问题讨论】:

    标签: split stream ocaml


    【解决方案1】:

    返回单位的函数是一种命令式函数,它会为它的副作用做一些事情并且不返回有用的值。

    如果你的函数都返回单位,你将如何累积你的单词列表?

    事实上,我在您的代码中的任何地方都没有看到这个累积的单词列表。

    事实是你可能想走另一条路。你想替换Stream.iter,这是一个带有副作用的命令式函数。相反,您很可能希望自己的函数调用 Stream.next 并返回一个累积值(而不是单位)。

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多