Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive expression whose only base case is an exception [Context: Reading from files in OCaml]
    primarykey
    data
    text
    <p><em><strong>Edit: Disregard this question! See comments below.</em></strong></p> <p>I want an OCaml expression which is passed a file (as an "in_channel"), then reads the file line by line, doing some processing, to the end, then returns the result of the processing.</p> <p>I wrote this test:</p> <pre><code>let rec sampler_string file string_so_far = try let line = input_line file in let first_two_letters = String.sub line 0 2 in sampler_string file (string_so_far ^ first_two_letters) with End_of_file -&gt; string_so_far;; let a = sampler_string (open_in Sys.argv.(1)) "";; </code></pre> <p>(Here the "doing some processing" is adding the first two characters of each line to a running tally, and the idea is that at the end a string containing the first two characters of every line should be returned.)</p> <p>This doesn't work: <strong>OCaml thinks that "sampler_string" produces something of type unit, rather than of type string</strong>. (Difficulties then occur later when I try to use the result as a string.) I think this problem is because <strong>the only base case happens in an exception</strong> (the End_of_file).</p> <p>So, a specific question and a general question:</p> <ol> <li>Is there a way to fix this code, by explicitly telling OCaml to expect that the result of sampler_string should be a string?</li> <li>Is there some standard, better syntax for a routine which reads a file line by line to the end, and returns the result of line-by-line processing?</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload