Search code examples
smlsmlnj

How can I define a heteregeneous list datatype?


I am just starting to learn SML and having issues. I want to define a datatype, for a list that is not homogeneous.
Take for example

val a = [1,[2,4,3],5,[2,6]] 

I have made this datatype

datatype 'a MulList = List of 'a multiList list
                    | E of 'a;

but I get the following error

/tmp/emacs-region29207RwC:8.34-8.43 Error: unbound type constructor: multiList

uncaught exception Error
  raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
             ../compiler/TopLevel/interact/evalloop.sml:44.55
             ../compiler/TopLevel/interact/evalloop.sml:296.17-296.20

Solution

  • Your datatype declarations has a few errors. First off it is good practice (as you do) to capitalise the first letter of the value constructors, however it is also good practice to have a type constructor in all lower case.
    The real error you have is that you reference your mullist type as multiList when you define the value constructor List.

    With that fixed, you can create your multilist:

    datatype 'a mullist = List of 'a mullist list
                        | E of 'a
    
    val a = [E 1, List [E 2, E 4, E 3], E 5, List [E 2, E 6]]