Search code examples
smlsmlnj

SML: define an array


Forgive me, if it's trivial but I am reading the documentation of arrays in SML and I am confused . I see many functions but how do I make my own array; How do I initialize one? (Everything , I tried failed)
For example a list is initialised like that :

 val l = [1,2,3];

if I wanted [1,2,3] to be an array 1x3 ?
I found how to initialize one array but with only one value like:

array(4,0) (*creates [0,0,0,0] *)

but what about the [1,2,3];


Solution

  • You have (at least) two possibilities for that, either using Array.fromList:

    val a = Array.fromList [1, 2, 3];
    

    either using Array.tabulate:

    fun incr x = x + 1;
    val a = Array.tabulate (3, incr);
    

    Array.tabulate takes two arguments: the size of your array and a function used to initialise the items of your array.

    val a = Array.tabulate (3, incr);
    

    is thus equivalent to:

    val a = Array.fromList [incr(0), incr(1), incr(2)];
    

    Note that I have defined a function incr but I could also have done:

    val a = Array.tabulate (3, fn x => x + 1);