<<     >>

APL Exercises 7
Indexing
 

⎕io←0 throughout.
 

7.0 Functions on Booleans

In mathematics, a function is a set of ordered pairs. (The ordered pairs are required to satisfy that if (x,y0) and (x,y1) are in the function, then y0=y1 .) A small domain (the x’s) offers the possibility of computing the function in a different way.

Use cmpx to compare the speed of the following pairs of functions:

   b←?1e5⍴2

   cmpx '1+b' '1 2[b]'
   cmpx '2×b' '0 2[b]'
   cmpx '*b'  '(*0 1)[b]'

7.1 Formatting Booleans

The APL primitive ⍕⍵ converts array into a character representation. Whenis boolean (0-1 values), the number of possible output for each element is rather limited. This fact was exploited in Dyalog APL version 15.0 to get a factor of 28 speed-up over version 14.1.

Write a function fmtbv ⍵ that models ⍕⍵ where is a boolean vector.

   b←?7⍴2
   fmtbv b
0 1 0 1 1 0 1
   ⍕b
0 1 0 1 1 0 1

   (⍕ ≡ fmtbv) b
1
   ⍴fmtbv b
13
   ⍴b
7

7.2 Functions on 1-Byte Integers

Dyalog APL has 1-byte integers as a datatype. There are only 256 1-byte integers and some functions are faster by indexing into a pre-computed table than by computing from scratch. For example:

   e←*¯128+⍳256          ⍝ pre-computed table

   x←¯128+?1e5⍴256
   ⎕dr x                 ⍝ check that x are 1-byte integers
83
   cmpx '*x' 'e[128+x]'  ⍝ which is faster?

It is not recommended that you as an APL programmer actually compute *x this way. (Too cumbersome and prone to errors in management.) The technique is however worthy of consideration for the APL implementer.
 

7.3 Parentheses Nesting

Write a function plevel ⍵ which produces the parenthesis nesting level for each element of string . For example:

   x←'⍵((∇S))⍵⌷⍨?≢⍵'

   plevel x
0 1 2 2 2 2 1 1 1 1 1 2 2 2 2 1 0 0 0 0 0 0 0

   x ,[¯0.5] plevel x
⍵ ( ( ∇ < S ) , = S , ( ∇ > S ) ) ⍵ ⌷ ⍨ ? ≢ ⍵
0 1 2 2 2 2 1 1 1 1 1 2 2 2 2 1 0 0 0 0 0 0 0

7.4 Bar Chart

Write a function bar ⍵ which produces a barchart.is a vector of non-negative integers.

   bar 3 1 4 1 5 9
⎕⎕⎕......
⎕........
⎕⎕⎕⎕.....
⎕........
⎕⎕⎕⎕⎕....
⎕⎕⎕⎕⎕⎕⎕⎕⎕