Generics in Wolfram Language
(* Starting with version 12.0, Wolfram Language has added support for
generics-like functionality through its Association pattern matching. *)
(* As an example of a generic-like function, SlicesIndex takes
a list of any type and an element of that type and returns
the index of the first occurrence of v in s, or -1 if not present. *)
SlicesIndex[s_List, v_] :=
Module[{index = FirstPosition[s, v]},
If[MissingQ[index], -1, First[index]]
]
(* As an example of a generic-like type, List is already a
built-in structure in Wolfram Language that can hold elements of any type. *)
(* We can define functions on generic-like types. Here's a simple LinkedList implementation: *)
ClearAll[LinkedList, node]
LinkedList[T_] := Association["head" -> None, "tail" -> None]
node[val_, next_: None] := Association["val" -> val, "next" -> next]
Push[lst_Association, v_] :=
Module[{newNode = node[v]},
If[lst["tail"] === None,
lst["head"] = newNode;
lst["tail"] = lst["head"],
lst["tail"]["next"] = newNode;
lst["tail"] = lst["tail"]["next"]
];
lst
]
(* AllElements returns all the LinkedList elements as a list. *)
AllElements[lst_Association] :=
Module[{elems = {}, current = lst["head"]},
While[current =!= None,
AppendTo[elems, current["val"]];
current = current["next"]
];
elems
]
(* Main function to demonstrate the usage *)
Main[] := Module[{s, intList},
s = {"foo", "bar", "zoo"};
(* When invoking generic-like functions, we don't need to specify types *)
Print["index of zoo: ", SlicesIndex[s, "zoo"]];
intList = LinkedList[Integer];
intList = Push[intList, 10];
intList = Push[intList, 13];
intList = Push[intList, 23];
Print["list: ", AllElements[intList]];
]
(* Run the main function *)
Main[]
This Wolfram Language code demonstrates concepts similar to generics in Go. Here’s a breakdown of the translation:
The
SlicesIndex
function is implemented using Wolfram Language’s pattern matching and list manipulation functions.Instead of defining a custom
List
type, we use Wolfram Language’s built-inList
which already supports elements of any type.The
LinkedList
is implemented using Associations, which are similar to dictionaries or maps in other languages.The
Push
andAllElements
functions are defined to work with ourLinkedList
implementation.The
Main
function demonstrates the usage of these generic-like structures and functions.
When you run this code in a Wolfram Language environment, you should see output similar to:
index of zoo: 3
list: {10, 13, 23}
Note that Wolfram Language uses 1-based indexing, so the index of “zoo” is 3 instead of 2.
While Wolfram Language doesn’t have explicit generics syntax like Go, its dynamic typing and pattern matching capabilities allow for similar flexibility in creating functions and data structures that work with multiple types.