0

This compiles:

let inputFile = open_in("test.txt");
let line = try(input_line(inputFile)) {
| End_of_file => "end of file"
};
print_endline(line);

But not this:

let inputFile = open_in("test.txt");
try(input_line(inputFile)) {
| line => print_endline(line)
| exception End_of_file => print_endline("end of file")
};

For the latter I get an error: "Exception patterns must be at the top level of a match case"

I'm confused because it seems like an identical pattern to the one in the docs (https://reasonml.github.io/docs/en/exception.html)

let theItem = "a";
let myItems = ["b","a","c"];
switch (List.find((i) => i === theItem, myItems)) {
| item => print_endline(item)
| exception Not_found => print_endline("No such item found!")
};

Which compiles without error.

Changing the order of the match cases, or removing the "exception" keyword, doesn't change the error.

What does this error mean? I'm not sure what "top level" means.

Robz
  • 1,747
  • 5
  • 21
  • 35

1 Answers1

2

try is used with exception(s) handling similar to try/catch in JavaScript. In your case, you want to do pattern matching and also catch an exception (which reasonml allows), so you could just use switch.

let inputFile = open_in("test.txt");
switch(input_line(inputFile)) {
| line => print_endline(line) 
| exception End_of_file => print_endline("end of file")
};
kimsk
  • 2,221
  • 22
  • 23
  • 2
    I think something worth mentioning, when designing functions that might fail in ReasonML, it is better to return the values in sum type like `Js.Result` which has `Ok` and `Error` constructors because the compiler will remind you to handle both cases, whereas it does not remind you to handle exceptions. However, many functions from the OCaml stdlib and lots of node functions use exceptions. – MCH May 14 '18 at 03:29