Arrays in Standard ML

In Standard ML, arrays are fixed-size sequences of elements of the same type. They are less commonly used than lists, but can be useful in certain scenarios.

(* Here we create an array 'a' that will hold exactly 5 integers. 
   The Array.array function takes the size and initial value as arguments. *)
val a = Array.array(5, 0)

(* We can print the array using Array.app and print *)
val _ = print "emp: "
val _ = Array.app (fn x => print (Int.toString x ^ " ")) a
val _ = print "\n"

(* We can set a value at an index using Array.update, 
   and get a value with Array.sub *)
val _ = Array.update(a, 4, 100)
val _ = print "set: "
val _ = Array.app (fn x => print (Int.toString x ^ " ")) a
val _ = print "\n"
val _ = print ("get: " ^ Int.toString(Array.sub(a, 4)) ^ "\n")

(* The Array.length function returns the length of an array *)
val _ = print ("len: " ^ Int.toString(Array.length a) ^ "\n")

(* We can create and initialize an array in one line using Array.fromList *)
val b = Array.fromList [1, 2, 3, 4, 5]
val _ = print "dcl: "
val _ = Array.app (fn x => print (Int.toString x ^ " ")) b
val _ = print "\n"

(* Standard ML doesn't have a direct equivalent to Go's [...] syntax or 
   index-based initialization. We can achieve similar results with functions *)
fun initArray n = 
    Array.tabulate(n, fn i => if i = 0 then 100 
                              else if i = 3 then 400 
                              else if i = 4 then 500 
                              else 0)

val c = initArray 5
val _ = print "idx: "
val _ = Array.app (fn x => print (Int.toString x ^ " ")) c
val _ = print "\n"

(* For multi-dimensional arrays, we can use arrays of arrays *)
val twoD = Array.tabulate(2, fn i => Array.tabulate(3, fn j => i + j))
val _ = print "2d: "
val _ = Array.app (fn row => 
            (print "[";
             Array.app (fn x => print (Int.toString x ^ " ")) row;
             print "] ")) twoD
val _ = print "\n"

(* We can also create and initialize multi-dimensional arrays at once *)
val twoD2 = Array.fromList [Array.fromList [1, 2, 3],
                            Array.fromList [1, 2, 3]]
val _ = print "2d: "
val _ = Array.app (fn row => 
            (print "[";
             Array.app (fn x => print (Int.toString x ^ " ")) row;
             print "] ")) twoD2
val _ = print "\n"

To run this program, you would typically save it in a file (e.g., arrays.sml) and then use an SML interpreter or compiler. For example, with the Standard ML of New Jersey (SML/NJ) system:

$ sml arrays.sml
emp: 0 0 0 0 0 
set: 0 0 0 0 100 
get: 100
len: 5
dcl: 1 2 3 4 5 
idx: 100 0 0 400 500 
2d: [0 1 2 ] [1 2 3 ] 
2d: [1 2 3 ] [1 2 3 ] 

Note that arrays in Standard ML are mutable, which is somewhat unusual for functional programming languages. In many cases, immutable data structures like lists are preferred in SML for their better compatibility with functional programming paradigms.