Range Over Built in Wolfram Language

Based on the language specified in the input, the target language for translation is Wolfram Language (Mathematica). Below is the translated Go code example in Wolfram Language along with explanations.

Range over Built-in Types

In this example, Range iterates over elements in a variety of built-in data structures. Let’s see how to use Range with some of the data structures we’ve already learned.

(* First, we define a list of numbers *)
nums = {2, 3, 4};

(* The Total function gives us the sum of the elements in the list *)
sum = Total[nums];
Print["sum: ", sum];

Here we use Range to sum the numbers in a list. Arrays work like this too.

(* List the elements with their indices and print the index when the element is 3 *)
Do[
  If[num == 3, Print["index: ", i]],
  {i, num} ∈ Transpose[{Range[Length[nums]], nums}]
];

Range on arrays and lists provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.

(* Define a dictionary *)
kvs = <|"a" -> "apple", "b" -> "banana"|>;

(* Iterate over key/value pairs in the dictionary *)
Do[
  Print[k, " -> ", v],
  {k, v} ∈ Normal[kvs]
];

Range on associations (dictionaries) iterates over key/value pairs.

(* Iterate over just the keys of a dictionary *)
Do[
  Print["key: ", k],
  {k} ∈ Keys[kvs]
];

Range can also iterate over just the keys of a dictionary.

(* Iterate over characters in a string and print their byte index and code point *)
string = "go";
Do[
  Print[i, " ", ToCharacterCode[string][[i+1]]],
  {i, Length[string]}
];

Range on strings iterates over Unicode code points. The first value is the starting byte index of the character and the second the character itself.

(* To run the program, simply execute the code in a Wolfram Language environment like Mathematica or WolframScript *)

Now that we can run and build basic Wolfram Language programs, let’s learn more about the language.