Does the `or` keyword have meaning in OCaml?

I wanted to define a helper function like such:

let my_func =
  let find key ~or = Option.value ~default:or @@ Hashtbl.find_opt tbl key in
  ...
  let val_ = find key ~or:[] in
  ...

But the compiler complained about a “syntax error”.

After a bit of digging, I realized or is a reserved keyword

So my question is: is there an actual use of it?

I know I can chain definitions with and, like such:

let x = 1 and y = 2 in

But it doesn’t look like or has meaning in OCaml, and will ever be used considering the usage of and (?)

or is an old name for the || operator.

Cheers,
Nicolas

Ah I see! Would it be reasonable to allow the programmer to use this now unused keyword?

I think that’s already possible, but it can only be used as an operator, not as a label:

let (or) = (+);;
val ( or ) : int -> int -> int = <fun>

I think people typically use or_ as a label, which works, but looks a bit weird.

1 Like

4.13.1:

# true or false;;
Alert deprecated: Stdlib.or
Use (||) instead.
- : bool = true

Manual says it is deprecated. Yet 5.1:

# true or false;;
Error: Unbound value or
# let or = "foo";;
Error: Syntax error
# let (or) = "foo";;
val ( or ) : string = "foo"

Looks like it is still reserved as an operator. Which was pointed out above.

1 Like

I like to define (or) as:

let (or) opt default =
  match opt with
  | None -> default
  | Some x -> x

This way you can use it as:

None or 42 (* 42 *)
Some 1 or 0 (* 1 *)
List.nth_opt [1; 2; 3] 5 or 0 (* 0 *)

Note that this is a low precedence operator, so you might need to use parens for complex expressions (or not use (or) at all).

14 Likes

That is much more elegant than Option.value myvar ~default: 0.

I’m going to steal the idea starting today :slight_smile:

1 Like

Cool idea.

It’s even clearer to define it this way: we can almost imagine “copy/pasting” the function’s definition in place.

let ( or ) opt default = Option.value ~default opt

let my_func =
  ...
  let curr = Hashtbl.find_opt tbl key or [] in
  (* vs *)
  let curr = Hashtbl.find_opt tbl key |> Option.value ~default:[] in

The only downside I can see with this approach is that it becomes a little less clear to a reader where the function ends, i.e. or looks like a third parameter to Hashtbl.find_opt.

It pops out with the site’s current syntax highlighting but not in vscode at least.

I’ll file a feature request. If we can define or as an operator, then it sounds to me like we should be allowed to use or as an identifier.

EDIT: somebody got there first :slight_smile:(or) operator for 'a option · Issue #12682 · ocaml/ocaml · GitHub

As a bit of history, the OCaml team removed ( or ) as an operator from the standard library and deprecated that keyword a long time ago. It’s probably more of an accident than anything else that it’s still around. I would suggest using another operator for this kind of ‘boolean-like’ logic, maybe ( |? ).