How do I read in lines from a text file in OCaml?

后端 未结 7 933
心在旅途
心在旅途 2020-12-31 02:18

This is what I have so far. Isn\'t this all that you need? I keep getting the error \"Error: Unbound module Std\"

let r file =
    let chan = open_in file in         


        
7条回答
  •  隐瞒了意图╮
    2020-12-31 02:57

    If you have the OCaml Core library installed, then it is as simple as:

    open Core.Std
    let r file = In_channel.read_lines file
    

    If you have corebuild installed, then you can just compile your code with it:

    corebuild filename.byte
    

    if your code resides in a file named filename.ml.

    If you don't have the OCaml Core, or do not want to install it, or some other standard library implementation, then, of course, you can implement it using a vanilla OCaml's standard library. There is a function input_line, defined in the Pervasives module, that is automatically opened in all OCaml programs (i.e. all its definitions are accessible without further clarification with a module name). This function accepts a value of type in_channel and returns a line, that was read from the channel. Using this function you can implement the required function:

    let read_lines name : string list =
      let ic = open_in name in
      let try_read () =
        try Some (input_line ic) with End_of_file -> None in
      let rec loop acc = match try_read () with
        | Some s -> loop (s :: acc)
        | None -> close_in ic; List.rev acc in
      loop []
    

    This implementation uses recursion, and is much more natural to OCaml programming.

提交回复
热议问题