3 ms·
>There’s an easy way to solve this: add an end if delimiter. Again: terseness bites. I think this is the second frontpage post in a single week with someone ta
by ubertaco 3y ago
>There’s an easy way to solve this: add an end if delimiter. Again: terseness bites.
I think this is the second frontpage post in a single week with someone talking about this exact thing, going on about how OCaml doesn't have braces or block-end signifiers....somehow completely missing `begin`...`end`, which has been part of the language since like forever?
Just like with the last post, let's look at this post's example:
let foo _ =
if true then
print_endline "Hello, world!";
true
else
false
Yeah, I'm a little surprised that this doesn't work, actually, since I would assume that it would parse the if-branch until it gets an expression, but the compiler (and OCamlFormat, for what it's worth) interprets this code like this (and the auto-formatting done by ocamlformat makes it clear what's going on -- maybe consider hooking that up as an on-save action in your editor):
let foo _ =
if true then
print_endline "Hello, world!";
true
else
false
(which I discovered by just copy-pasting it directly into https://try.ocamlpro.com https://try.ocamlpro.com, which auto-formatted the code exactly like that for me).
Basically "(if true then print); true" rather than "if true then (print; true)"
Getting back to my original point, the code can easily be fixed by using `begin` and `end`:
let foo _ =
if true then begin
print_endline "Hello, world!";
true
end
else
false
OCaml _does_ have braces, like in the "more-solid-feeling" languages the author describes. They're just named "begin" and "end" instead of "{" and "}", same as in Ruby or Elixir or Pascal or even Austral (which is the author's own language).
This is, admittedly, more of a pain for dropping in a quick debug statement than what the author found:
let foo _ =
if true then
let _ = print_endline "Hello, world!" in
true
else
false
...which honestly, for the "quickly add a print-debug line" case, doesn't seem like a problem?