Other data types and constructs

  1. Lists

    Shang does not have cell array, but it has a host of data structures in addition to numerical matrices. Among these data structures, lists are arrays whose elements can be anything, including matrices, strings, functions, tables, structures, and objects. Lists might function similarly to the cell arrays of Matlab.

  2. Pointer and Pass by reference

    Shang passes function arguments strictly by value. However, by using pointer, it's possible to emulate passing by reference. The following is how the swap function can be implemented

    swap = function (p, q) -> ()
         temp = p>>;  // store in temp the value pointed to by p
         p>> = q>>;   // p now points to the value pointed by q
         q>> = temp;  // q now points to temp
    end
    
    The caller must pass two pointers to the swap function
    >> a = "AAA";
    >> b = "BBB";
    >> swap(>>a, >>b);
    >> a, b
       BBB
       AAA
    end
    
    If you want to alter an argument value, you also have to pass a pointer. For example
    f = function (p, k, x) -> ()
          p>> [k] = x;
    end
    
    Test it
    >> x = zeros(1, 3);
    >> f(>>x, 2, rand(1));
    >> x
       0  0.239  0
    

  3. Hash Table

    A hash table is a set of key-value pairs. Each value can be retrieved by providing the associated key. Here is how you can create a hash table, retrieve a value, add key-value pair, and update values:

    >> A = {"red" => "maple", "purple" => "lilac", "grey" => "ash"}
    >> A @ "purple"
       lilac
    >> A @ "violet" = "lavender";
    
    A hash table can also act like a function, therefore in the above A("purple") returns lilac as well.

  4. Structure

    A structure is a group of attribute values with each one associated with an identifier. It is very easy to create by using a pair of braces. Each attribute is declared and initialized by assigning the value to the identifier, and all attributes are enclosed in a pair of braces. For example

    >> dims = {length = 15, width = 10, height = 9,
               verify = () -> parent.length * parent.width * parent.heigth <= 1000};
    >> dims.height
       9
    >> dims.height = 12
    >> dims.height
       12
    
    Note that since function is also a data type, attributes of a structure can be functions as well. For example
    >> dims = {length = 15, width = 10, height = 9,
               verify = () -> parent.length * parent.width * parent.height <= 1000};
    >> dims.verify()
       0
    

  5. Stack and Queue

oz 2009-12-22