Saturday, August 18, 2012

Boxes

We have seen 1D arrays and multi-dimensional numerical arrays. But what if we want a structure to hold different types of data? For example, we can create a structure, a box, containing both numeric and charcter data.
First we will have a quick introduction to character data.

      charlist =: 'Hello world!'

This creates a D character array. We can use the indexing verbs "{" and "}" to find sublists.

      1{charlist
      e

1} asks for the element of charlist at position 1, similar to C's charlist[1].

      1 2 3{ charlist
      ell

Here we took the 1st, 2nd and 3rd elements of the char array.
We can combine two lists thus.

   charlist =: ' Hello ' , 'world!'

where "," is the verb for concatenating elements.

OK. So what if I try to concat a character list with a numerical list?

    somelist =: 'A phrase', 1 2 3
    | domain error
    |   somelist=:'A phrase'    ,1 2 3

Uh oh. Big problem. The interpreter doesn't want us to do that.
But we can make a "box" to hold both numeric and character data. Here is how:

     char =: 'some important info'
   num =: 1924 1945 1986 1998
   box =: (<char),(<num)
   
   box
┌───────────────────┬───────────────────┐
│some important info│1924 1945 1986 1998│

So the box, which is a scalar object, i.e. it has no size (check $#box), contains one element of char data and one of numerical.

We can search the box to find the data:

         >num
        1924 1945 1986 1998

finds the data corresponding to "num".
We can also go further and make tables of data. For example:


       char1 =: 'important dates'
     char2 =: 'notes'
     num1 =: 15 2
     num2 =: 17 5
     num3 =: 25 12
                        
     note1 =: 'birthday'
     note2 =: 'anniversary'
     note3 =: 'Christmas'


     datebox =: (<char1),<char2
     dates1=: (<num1),<note1
     dates2=: (<num2),<note2
     dates3=: (<num3),<note3

     ((datebox,:dates1),dates2),dates3
┌───────────────┬───────────┐
│important dates│notes      │
├───────────────┼───────────┤
│15 2           │birthday   │
├───────────────┼───────────┤
│17 5           │anniversary│
├───────────────┼───────────┤
│22 11          │Christmas  │
└───────────────┴───────────┘


Here we used the useful dyadic verb ",:", "laminate" which sticks one array on top of another.
An example:

    a1 =: 1 2 3 4
    a2 =: 2 4 6 8
    
    a1,:a2

   1 2 3 4
   2 4 6 8

What about:

    a1 =: 1 2 3 
    a2 =: 2 4 6 8
    
    a1,:a2
    1 2 3 0
    2 4 6 8

The interpreter appends a zero to the top array, as it sees there are too few elements.







No comments:

Post a Comment