Reputation: 293
I'm trying to read from a file in OCaml and break each line into a list of strings delimited by spaces and then append that list to a cumulative list. The error I'm receiving is:
File "bin/scanner.ml", line 17, characters 25-42:
Error: This expression has type string list
but an expression was expected of type unit
My entire program (scanner.ml) is:
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 ;;
I think I understand that the error is that split_space returns a list of strings while the anonymous function in line 17 expects a function returning type unit. What I am stuck on is how I can modify split_spaces so that its return type is unit.
Upvotes: 0
Views: 668
Reputation: 66803
A function that returns unit is an imperative-style function that does something for its side effect and doesn't return a useful value.
If your functions all return unit, how will you accumulate your list of words?
In fact I don't see this cumulative list of words anywhere in your code.
The fact is you probably want to go the other way. You want to replace Stream.iter
, which is an imperative function with side effects. Instead you most likely want your own function that calls Stream.next
and returns an accumulated value (rather than unit).
Upvotes: 1