Range Over Built in Chapel

### Range over Built-in Types

*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.

```chapel
// Chapel program that demonstrates range over built-in types

// Sum the numbers in a list.
var nums = [2, 3, 4];
var sum = 0;

for num in nums {
  sum += num;
}
writeln("sum: ", sum);

// Using range with indices
for (i, num) in zip(nums.domain, nums) {
  if num == 3 {
    writeln("index: ", i);
  }
}

// Iterating over key/value pairs in a map.
var kvs = ["a" => "apple", "b" => "banana"];
for (k, v) in kvs {
  writeln(k, " -> ", v);
}

// Iterating over just the keys of a map.
for k in kvs.keys() {
  writeln("key: ", k);
}

// Iterating over characters in a string
for (i, c) in zip(0..#'go'.localeToIndex('go'), 'go'.codepoints()) {
  writeln(i, " ", c);
}

To run the program, save the code in a file with a .chpl extension and use the chpl compiler to compile and run it.

$ chpl example.chpl -o example
$ ./example
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Chapel’s for loops and iterations provide powerful and flexible ways to work with various data structures. Let’s dive into more advanced features of the language in the next examples.

查看推荐产品