Working With Lists

ASTRA provides built in support for lists, which are basically dynamic arrays. As is normal in logics, lists are untyped. This means that they can contain different types of term. ASTRA itself contains little direct support for manipulating lists. Instead most functionality is provided through the Prelude API.

To return the the User Guide click here.

Declaring a List

To declare a list, you use square brackets inside which there is a comma-delimited list of the elements of that list. The example below declares a list of three strings “a”, “b”, and “c”:

  [ "a", "b", "c" ]

Lists can also be used in conjunction with list variables, for example the code below assigns the above list to a variable L:

  list L = [ "a", "b", "c" ];

To append one list to another you use the + operator:

  list L = [ "a", "b" ] + [ "c" ];

Iterating through Lists

To iterate through a list, you need to make use of the Prelude API. For example, the program below iterates through a statically defined list of strings and prints them out:

  package examples;
  
  agent Listy {
      module Prelude prelude;
      module Console console;
      
      initial !init();
      
      rule +!init() {
          list L = [ "a", "b", "c", "d", "e" ];
          
          int i = 0;
          while (i < prelude.size(L)) {
              console.println(prelude.valueAsString(L, i));
              i = i + 1;
          }
      }
  }

Example: Shuffle and Sort

This program creates an initial list of 5 elements, shuffles them, prints out the shuffled list, sorts the list, and finally prints out the sorted list.

  package examples;
  
  agent ShuffleSort {
      module Console console;
      module System system;
      module Prelude prelude;
      module Math math;

      rule +!main(list args) {
          list l = [ "a", "b", "c", "d", "e" ];
          !shuffle(l, list l2, 10);
          console.println("shuffled: " + l2);
          l2 = prelude.sort_asc(l2);
          console.println("sorted: " + l2);
          system.exit();
      }

      rule +!shuffle(list in, list out, int N) {
          out = in;
          int i=0;
          while (i < N) {
              int j = math.randomInt() % prelude.size(out);
              int k = math.randomInt() % prelude.size(out);
              out = prelude.swap(out, j, k);
              i = i + 1;
          }
      }
  }