Samuele B.
Samuele B.

Reputation: 658

Polymorphic types in OCaml

Let's say I want to create a set type in OCaml. I want it to be either empty, or represented by a list of type 'a.

I have the following definition:

type 'a set_ = Empty | Set of 'a list;;

If I want to create an "expressable type" type, which includes integers, booleans, string literals, and sets, I am not sure how to go about it. I tried the following:

type exType = Int of int | Bool of bool | String of string | EmptySet of Empty | StringSet of string Set | BoolSet of bool Set | IntSet of int Set

but I get a syntax error (and no more information) which underlines the | character which follows EmptySet of Empty immediately.

What's the correct way of implementing what I'm after?

Upvotes: 0

Views: 110

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

The identifier Empty is not a type, it's a value. Type names start with lower-case letters, hence this is actually a syntax error.

(In OCaml capitalized identifiers and uncapitalized identifiers are in different syntactic categories.)

You'll have to decide on another plan for the empty set. Since it's empty it doesn't really need any associated data (I would think). So you could just have:

. . . | EmptySet | . . .

perhaps.

Update

Again, Set is a value (actually a value constructor) not a type. You want this (I'm pretty sure):

StringSet of string set_

Again one clue is that type names start with lower-case letters.

Upvotes: 2

Related Questions