Trung Bún
Trung Bún

Reputation: 1147

OCaml: unspecified type variables

Is there anyway to define a variable that match any type in OCaml?

I came up with this: type term = Save of '_

after reading this tutorial

But it doesn't work.

Error: Syntax error

Could someone tell me why I have the error in the code above?

Upvotes: 0

Views: 316

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

A single underscore _ is more of an operator (a pattern, usually) than an identifier in OCaml. So that's your syntax problem. Furthermore, a type variable name can't start with an underscore. If you change to a legal name like 'a, you see the following:

# type term = Save of 'a;;
Error: Unbound type parameter 'a
# 

It's not at all clear what you're trying to do, but the most straightforward definition that's similar to what you give might be this:

# type 'a term = Save of 'a;;
type 'a term = Save of 'a

Then you can have values with any type as the contents:

# Save 33;;
- : int term = Save 33
# Save "yes";;
- : string term = Save "yes"
# 

I suspect you're trying to do something fancier than this, but if so you'll need to explain it more carefully (at least for me :-).

Upvotes: 3

Andreas Rossberg
Andreas Rossberg

Reputation: 36078

Every type variable matches "any type" in OCaml. However, all type variables in a type definition have to be bound, usually as a parameter:

type 'a term = Save of 'a

The data constructor defined here will have type Save : 'a -> 'a term. Consequently, in a value of type int term, the constructor is known to carry an integer.

But I'm not sure what you are trying to achieve. Maybe you also want an existential type, which "forgets" the type the variable is instantiated with? Then you need to use GADT syntax:

type term = Save : 'a -> term

Here, the data constructor will have type Save : 'a -> term. However, this type is not particularly useful, since you cannot do anything with the constructor's argument later, as it will be fully abstract when you match it (because it can be anything, and there is no way to tell what it is at that point -- unlike with the type above). So without understanding your use case, it's difficult to give a better answer.

Upvotes: 4

Related Questions