Question

This is one example of code that I would imagine work work fine in a set data type implemented as a list:

fun newSet() = nilset;

fun isMember (k, x::xs) = if k = x then true else isMember (k, xs)
  | isMember (k, nilset) = false;

The problem is that I cannot implement it as a list. Below is the code for the implementation of my set.

abstype ''a set = nilset | st of ''a * ''a set

How can I recursively do this and other set operations if :: is for lists? If it's not, why is this throwing exceptions? I get this when I use :::

! Type clash: pattern of type
!   ''a set
! cannot have type
!   ''b list

Thanks for any help.

Was it helpful?

Solution

It isn't an exception; it is a type error saying that you can't use cons constructor :: belonging to 'a list with 'a set.

Assuming that you have two constructors Nilset and Set in a recursive datatype:

datatype 'a set = Nilset | Set of 'a * 'a set

You should follow the recursive structure of your datatype to define isMember:

fun isMember (k, Set(x, xs)) = k = x orelse isMember (k, xs)
  | isMember (k, Nilset) = false

Certainly, for serious use of Set, you should look into Set structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top