z_axis
z_axis

Reputation: 8460

What's the difference with or without backtick "`"?

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

Can i remove the "`" here ?

Sincerely!

Upvotes: 16

Views: 4253

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

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.

Upvotes: 13

Related Questions