Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `B means?

Tags:

ocaml

In toplevel, i get the following output:

#`B
- : [> `B ] = `B

then what does `B mean ? Why do we need it ?

Sincerely!

like image 837
z_axis Avatar asked Jan 16 '23 02:01

z_axis


1 Answers

An identifier prefixed with a backquote like `B is a constructor of a polymorphic variant type. It's similar to the constructor of an algebraic type:

type abc = A | B | C

However, you can use polymorphic variant values without declaring them, and in general they're much more flexible than the usual algebraic types. The tradeoff is that they're also quite a bit trickier to use.

One thing people use them for is as simple named values, like enum values in C. Or, more precisely, like atoms in Lisp. You can use ordinary algebraic types for this, but you need to carefully maintain your definitions of them and guard against duplication. With polymorphic variants, you don't need to do either of these. You can use them without declaring them, and the constructors aren't required to be unique (two different types can have the same constructor).

Polymorphic variant constructors can also take parameters, as algebraic constructors can. So you can also write (`B 77), a constructor with a single int parameter.

This is a pretty big topic--see the above linked section of the OCaml manual for more details.

like image 117
Jeffrey Scofield Avatar answered Jan 25 '23 17:01

Jeffrey Scofield