Slices in Standard ML

(* Lists are an important data type in Standard ML, providing
   a powerful interface for working with sequences of elements. *)

(* Unlike arrays, lists in SML are homogeneous, meaning all elements
   must be of the same type. An empty list is represented by []. *)
val emptyList : string list = [];
val _ = print("uninit: " ^ (if null emptyList then "true" else "false") ^ " " ^
              (if length emptyList = 0 then "true\n" else "false\n"));

(* To create a list with elements, we can use the :: (cons) operator
   or list literals with square brackets. *)
val s = ["a", "b", "c"];
val _ = print("set: " ^ String.concatWith " " s ^ "\n");
val _ = print("get: " ^ List.nth(s, 2) ^ "\n");

(* length returns the number of elements in the list *)
val _ = print("len: " ^ Int.toString(length s) ^ "\n");

(* We can add elements to the beginning of a list using :: *)
val s = "d" :: s;
val s = "e" :: "f" :: s;
val _ = print("apd: " ^ String.concatWith " " s ^ "\n");

(* Lists can be concatenated using the @ operator *)
val c = ["g", "h", "i"];
val s = s @ c;
val _ = print("cpy: " ^ String.concatWith " " s ^ "\n");

(* We can use pattern matching to deconstruct lists *)
val [x, y, z] = ["a", "b", "c"];
val _ = print("dcl: " ^ x ^ " " ^ y ^ " " ^ z ^ "\n");

(* Standard ML provides various utility functions for working with lists *)
val t = ["g", "h", "i"];
val t2 = ["g", "h", "i"];
val _ = if t = t2 then print("t == t2\n") else ();

(* We can create lists of lists to represent multi-dimensional data structures *)
val twoD = [
    [0],
    [1, 2],
    [2, 3, 4]
];
val _ = print("2d: " ^ String.concatWith " " (map (fn l => "[" ^ String.concatWith "," (map Int.toString l) ^ "]") twoD) ^ "\n");

In Standard ML, lists are the primary sequential data structure, similar to slices in Go. However, there are some key differences:

  1. SML lists are homogeneous (all elements must be of the same type), while Go slices can be heterogeneous.
  2. SML lists are immutable, whereas Go slices are mutable.
  3. Adding elements to an SML list creates a new list, while appending to a Go slice modifies the existing slice.

The concepts of slicing and appending in Go are replaced with list operations like :: (cons), @ (concatenation), and functions from the List structure in SML.

Pattern matching in SML provides a powerful way to work with lists, which is not available in Go.

Note that SML doesn’t have a direct equivalent to Go’s make function for creating slices. Instead, lists are typically built using cons (::) or list literals.

The slices package utilities in Go can be mostly replaced by functions from the List structure in SML’s standard library.

While Go slices can have varying lengths in multi-dimensional structures, SML lists of lists can naturally have varying lengths without any special handling.