15
type level =
[ `Debug
| `Info
| `Warning
| `Error]

Can i remove the "`" here ?

Sincerely!

z_axis
  • 8,272
  • 7
  • 41
  • 61
  • This is related (somewhat) to: http://stackoverflow.com/questions/1746743/extending-an-existing-type-in-ocaml/1747400#1747400 – Rémi Nov 22 '11 at 04:25

1 Answers1

12

It's hard to answer this question yes or no.

You can remove the backticks and the square brackets. Then you would have

type level2 = Debug | Info | Warning | Error

In the simplest cases, this type is is very similar to your type level. It has 4 constant constructors.

In more complex cases, though, the types are quite different. Your type level is a polymorphic variant type, which is more flexible than level2 above. The constructors of level can appear in any number of different types in the same scope, and level participates in subtyping relations:

# type level = [`Debug | `Info | `Warning | `Error]
# type levelx = [`Debug | `Info | `Warning | `Error | `Fatal]

# let isfatal (l: levelx) = l = `Fatal;;
val isfatal : levelx -> bool = <fun>
# let (x : level) = `Info;;
val x : level = `Info
# isfatal (x :> levelx);;
- : bool = false

The point of this example is that even though x has type level, it can be treated as though it were of type levelx also, because level is a subtype of levelx.

There are no subtyping relations between non-polymorphic variant types like level2, and in fact you can't use the same constructor name in more than one such type in the same scope.

Polymorphic variant types can also be open-ended. It's a big topic; if you're interested you should see section 4.2 of the OCaml manual, linked above.

SeedyROM
  • 2,203
  • 1
  • 18
  • 22
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • 1
    afair, the preferrable name now is "open variants". – ygrek Nov 25 '11 at 10:01
  • I thought open variants referred to things like exceptions? also does levelx need to be a subset or superset of level here? Can it just be an intersection? Can it mix backtick variants and non-backtick variants? – David 天宇 Wong Apr 16 '21 at 20:46
  • Is [4.2 Labels and type interference](https://v2.ocaml.org/manual/lablexamples.html#s:label-inference) really the section you mean? – cafce25 Jul 21 '23 at 07:07