147pm
147pm

Reputation: 2239

SML: datatype declaration won't allow []

The standard SML Basis list is defined as

datatype 'a list = [] | :: of 'a * 'a list

However, I get this error when I try to create my own list data type:

- datatype 'a mylist = [] | mycons of 'a * 'a mylist
 Error: syntax error found at LBRACKET

However, this works:

- datatype 'a mylist = Nil | mycons of 'a * 'a mylist;
datatype 'a mylist = Mycons of 'a * 'a mylist | Nil

But due to the lack of square brackets, this verson doesn't produce very list-like output:

- Mycons (1,Nil);
val it = Mycons (1,Nil) : int mylist
- Mycons (1, Mycons (1,Nil));
val it = Mycons (1,Mycons (1,Nil)) : int mylist

Why isn't SML accepting my original attempt with []?

Upvotes: 0

Views: 103

Answers (1)

ruakh
ruakh

Reputation: 183241

This:

The standard SML Basis list is defined as

datatype 'a list = [] | :: of 'a * 'a list

is not correct.

Rather, list is defined like this:

datatype 'a list = nil | :: of 'a * 'a list

and the [foo, bar, baz] notation is a special syntax (a "derived form") that the Definition of Standard ML, Revised explicitly defines (in Appendix A, on page 56) as being equivalent to foo :: bar :: baz :: nil.


For your type, you're not going to be able to redefine the [...] syntax — it is built into the language, and its meaning is fixed — but you can make your syntax at least somewhat friendlier by using a symbolic (non-alphanumeric) identifier and declaring it as infix and right-associative; for example:

infixr :::

datatype 'a my_list = MY_NIL | ::: of 'a * 'a my_list

val twoOnes = 1 ::: 1 ::: MY_NIL

Upvotes: 2

Related Questions