Saturday, February 22, 2014

Arrays and Indexers in Zonnon



Today's post is about Arrays and Indexers in Zonnon. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Zonnon, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and Oxygene just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on Zonnon Builder and run it.

Last thing. There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.

(*****************************************
String Utilities Module
*****************************************)

module Str;

type {private} MArrayOfChar = array {math} * of char;
type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;

procedure {public} CountWords(s: array * of char; sep: char): integer;
var i,slen,wlen,c: integer;
begin
  slen := len(s)-1;
  c := 0;
  for i := 0 to slen do
 wlen := 0;
 while (i < slen) & (s[i] # sep) do inc(wlen); inc(i); end;
 if (i <= slen) & (wlen > 0) then inc(c) end; 
  end;
  return c;
end CountWords;

procedure {public} Split(s: string; sep: char)
 : array * of string;
var i,j,k,slen,wlen,pos: integer;
 l: array * of char;
 a: array * of string;
begin
  l := new ArrayOfChar(len(s)+1);
  copy(s, l);
  slen := len(l)-1;
  a := new ArrayOfString(CountWords(l,sep));
  pos := 0; k := 0;
  for i := 0 to slen do
 wlen := 0;
 while (i < slen) & (l[i] # sep) do inc(wlen); inc(i); end;
 if (i <= slen) & (wlen > 0) then 
   if (i <= slen) then a[k] := s.Substring(pos,wlen); inc(k) end;
   for j := 0 to wlen do inc(pos) end;
 end; 
  end;
  return a;
end Split;

procedure {public} Join(c: char; arr: array {math} * of char): string;
var i: integer;
 s: string;
begin
  s := "";
  for i := 0 to len(arr) - 1 do
    s := s + string(arr[i]) + string(c);
  end;
  if len(s) == 0 then return s end;
  return s.Substring(0,s.LastIndexOf(c));
end Join;

end Str.

(*****************************************
Alphabet Object
*****************************************)

object {ref} Alphabet(asize: integer; astr: string; achar: array * of char) 
 implements [];

import Str;

type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;

(* Array Field *) 
var {private} letters: array {math} * of char;  

(* Indexer Get/Set Property *)
procedure {public} Get(i: integer): char implements [].Get;
begin 
  return self.letters[i];
end Get;
procedure {public} Set(i: integer; c: char) implements [].Set;
var s: string;
begin
  s := string(c); 
  if ~(s = s.ToUpper()) then s := s.ToUpper(); c := s[0] end;
  self.letters[i] := c; 
end Set;

(* No Property, Getter instead *)
procedure {public} GetLength: integer; 
begin 
  return len(self.letters); 
end GetLength;  

(* Override Method *)
procedure {public} ToString: string implements System.Object.ToString;
begin
  return Str.Join(char(','), self.letters);
end ToString;

(* Method *)
procedure {public} Slice(start: integer; length: integer)
  : array  * of char;
var l: integer;
 a: array  * of char;
begin
  a := new ArrayOfChar(len(self.letters));
  a := self.letters[start..length-1];
  return a;
end Slice;

(* No Overloaded Constructors Support in v 1.3.0 *)
(* Contructor | Initializer *) 
begin   
  if asize # 0 then
    self.letters := new ArrayOfChar(asize);
  elsif astr # nil then
    self.letters := new ArrayOfChar(len(astr));
    copy(astr.ToUpper(),self.letters);
  elsif achar # nil then
    self.letters := achar;
  else
    self.letters := new ArrayOfChar(0);  
  end;  
end Alphabet.


(*****************************************
Program Module
*****************************************)

module Main;  
import System.Random as Random,
 Str, Alphabet;

type {private} ArrayOfChar = array * of char;
type {private} ArrayOfString = array * of string;
type {private} ArrayMatrix = array {math} *,* of integer;
type {private} JaggedArrayOfString = array * of array * of string;


procedure ReverseChar(var arr: array * of char)
 : array * of char;
var 
  reversed: array * of char; 
  i,j: integer;
begin
  i := 0;
  reversed := new ArrayOfChar(len(arr));
  for j := len(arr,0)-1 to 0 by -1 do  
    reversed[i] := arr[j];  
    inc(i);
  end;
  return reversed;
end ReverseChar;

procedure BubbleSortInt(var arr: array {math} * of integer)
 : array {math} * of integer;   
var i, j, swap: integer;  
begin  
  swap := 0;  
  for i := len(arr) - 1 to 1 by -1 do  
    for j := 0 to i - 1 do  
      if arr[j] > arr[j + 1] then  
        swap := arr[j];    
        arr[j] := arr[j + 1];    
        arr[j + 1] := swap;   
      end;  
    end;  
  end;  
  return arr;  
end BubbleSortInt;  

procedure BubbleSortString(var arr: array * of string)
 : array * of string;   
var 
  i, j: integer;  
  swap: string;
begin  
  swap := "";  
  for i := len(arr) - 1 to 1 by -1 do  
    for j := 0 to i - 1 do  
      if arr[j,0] > arr[j + 1,0] then  
        swap := arr[j];    
        arr[j] := arr[j + 1];    
        arr[j + 1] := swap;   
      end;  
    end;  
  end;  
  return arr;  
end BubbleSortString; 

procedure TransposeMatrix(m: array {math} *,* of integer)
 : array {math} *,* of integer;  
var   
  i, j: integer;
  transposed: array {math} *,* of integer;    
begin  
  (* Transposing a Matrix 2,3   
   *   
   * A =  [6  4 24]T [ 6  1]   
   *      [1 -9  8]  [ 4 -9]  
   *                 [24  8]  
   *)    
  transposed := new ArrayMatrix(len(m, 1), len(m, 0));
  for i := 0 to len(m,0) - 1 do 
    for j := 0 to len(m,1) - 1 do 
      transposed[j, i] := m[i, j];    
    end;  
  end;  
  return transposed;  
end TransposeMatrix;  

procedure UpperCaseRandomArray(arr: array * of array * of string); 
var r: Random; 
 i,j: integer;
 s: string; 
begin 
  r := new Random; 
  i := r.Next(0, len(arr) - 1); 
  for j := 0 to len(arr[i]) - 1 do 
 s := arr[i,j];
    arr[i,j] := s.ToUpper();
  end; 
end UpperCaseRandomArray; 

procedure PrintArrayChar(var arr: array * of char);
begin
  writeln("Print Array Content Char[":0,string(len(arr)):0,"]":0);
  for i := 0 to len(arr, 0) - 1 do
    writeln(" array [",i:2,"] = ",arr[i]:2," ");
  end;
  writeln;
end PrintArrayChar;

procedure PrintArrayInt(var arr: array {math} * of integer);
begin
  writeln("Print Array Content Int32[":0, string(len(arr)):0, "]":0);
  for i := 0 to len(arr, 0) - 1 do
    writeln(" array [",i:2,"] = ",arr[i]:2," ");
  end;
  writeln;
end PrintArrayInt;

procedure PrintArrayString(var arr: array * of string);
begin
  writeln("Print Array Content String[":0, string(len(arr)):0, "]":0);
  for i := 0 to len(arr, 0) - 1 do
    writeln(" array [",i:2,"] = ",arr[i]:2," ");
  end;
  writeln;
end PrintArrayString;

procedure PrintMatrix(m: array {math} *,* of integer);   
var i,j: integer;
begin  
  writeln("Print Matrix Content Int32[":0, string(len(m,0)):0, ",":0, string(len(m,1)):0, "]":0); 
  
  for i := 0 to len(m,0) - 1 do 
    for j := 0 to len(m,1) - 1 do  
   writeln(" array [":0,i:2,j:2,"] = ",m[i, j]:2," ":0);
    end;  
  end;   
  writeln;
end PrintMatrix;  

procedure GraphJaggedArray(arr: array * of array * of string); 
var lineCount: integer; 
 i,j: integer;
begin
  writeln;
  writeln("Print Text Content String[][]":0); 
  lineCount := 1; 
  for i := 0 to len(arr) - 1 do 
    write("Line":0,lineCount:2,"|":0); 
 for j := 0 to len(arr[i]) - 1 do 
      write("*":3);
    end; 
    writeln(" (":0,string(len(arr[i])):0,")":0); 
    inc(lineCount);
  end; 
  writeln;
end GraphJaggedArray; 

procedure PrintJaggedArray(arr: array * of array * of string); 
var i,j: integer;
 line: string; 
 linearr: array * of string;
begin 
  writeln;
  writeln("Print Jagged Array Content String[][]":0); 
  for i := 0 to len(arr) - 1 do 
    line := "";
    for j := 0 to len(arr[i]) - 1 do 
      line := line + " " + arr[i,j];   
    end; 
    if line = line.ToUpper() then 
   line := line + " <-- [UPPERCASED]"; 
    end; 
    writeln(line:0);
  end; 
end PrintJaggedArray; 

procedure PrintCommonArrayExceptions(arr: array * of array * of string); 
(* 
"Extra information about the exception can be accessed 
by calling the predefined function 'reason'. This causes the 
runtime system to return a string which explains the reason 
for the exception." Not working in Zonnon version 1.3.0
var s: string;
do ... on exception do
s := reason; <- This gives a "reason not declared" error at compile time.
end; 
*)
begin 
  do 
    arr[100,100] := 'hola'; 
  on NilReference do
    writeln;
    writeln("Exception: NilReference":0);
  on OutOfRange do
    writeln;
    writeln("Exception: OutOfRange":0);
  on exception do  
    writeln;
    writeln("Exception: Other":0); 
  on termination do
    (* nothing *)
  end; 
  writeln;
end PrintCommonArrayExceptions; 

procedure PrintTitle(message: string);   
begin  
  writeln('======================================================':0);
  writeln(message:0);
  writeln('======================================================':0);
  writeln;
end PrintTitle;  

var
(*writeln(pos,wlen,Substring(s,pos,wlen),s.Substring(pos,wlen));*)
  i: integer;
  (* Declare Array of Chars *)
  letters: array 5 of char;
  inverse_letters: array * of char;

  (* Mathematical extensions
  Mathematical extensions of Zonnon let use arrays in a more convenient way 
  for writing applications where multidimensional algebra is used. 
  Arrays to be used in mathematical extensions should be defined with special
  {math} modifier. ArrayType = array "{" math "}" Length {"," Length} of Type.
  This option allow you to initialize math array with array expressions, 
  but it only works for numerical arrays such as 
  array {math} of integer | real | boolean but not of string.
  *)

  (* Declare Array of Integers *)
  numbers, ordered_numbers: array {math} * of integer;
  (* Declare Array of Strings *)
  names: array 5 of string;
  ordered_names: array * of string;
  (* Declare multi-dimensional Array *)
  matrix: array {math} 2, 3 of integer;
  transposed_matrix: array {math} *,* of integer;
  (* Declare Jagged Array *)
  text: array * of array * of string;
  (* Indexer *)
  vowels,en,na: Alphabet;
  vs,w: array {math} * of char;
  word1,word2,word3: string;
begin  
  (* Single-dimensional Array(s) *)
  PrintTitle("Reverse Array Elements"); 

  (* Initialize Array of Chars  *)
  letters[0] := 'A';
  letters[1] := 'E';  
  letters[2] := 'I';  
  letters[3] := 'O';  
  letters[4] := 'U'; 

  PrintArrayChar(letters);   
  inverse_letters := ReverseChar(letters);    
  PrintArrayChar(inverse_letters); 
  
  PrintTitle("Sort Integer Array Elements");  

  (* Initialize Math Array of Integers *)
  numbers := [ 10, 8, 3, 1, 5];    
  PrintArrayInt(numbers);
  ordered_numbers := BubbleSortInt(numbers);    
  PrintArrayInt(ordered_numbers);
  
  PrintTitle("Sort String Array Elements");    
    
  (* Initialize Array of Strings *)
  names[0] := "Damian";     
  names[1] := "Rogelio"; 
  names[2] := "Carlos";     
  names[3] := "Luis";               
  names[4] := "Daniel";    
  PrintArrayString(names);  
  ordered_names := BubbleSortString(names);     
  PrintArrayString(ordered_names);

  (* Multi-dimensional Array (Matrix row,column) *)
    
  PrintTitle("Transpose Matrix");    
    
  (* Matrix row=2,col=3  
   * A =  [6  4 24]  
   *      [1 -9  8]  
  *)    
  (* Array inline expression used to declare and initialize array *)
  matrix := [[6, 4, 24], 
    [1, -9, 8]];   

  PrintMatrix(matrix);    
  transposed_matrix := TransposeMatrix(matrix);    
  PrintMatrix(transposed_matrix);
  
  (* Jagged Array (Array-of-Arrays) *)
    
  PrintTitle("Upper Case Random Array & Graph Number of Elements");
  
  (*
  * Creating an array of System.String arrays using the (System.)String.Split method
  *
  * Text extract from: 'El ingenioso hidalgo don Quijote de la Mancha'  
  *   
  *)
  text := new JaggedArrayOfString(8,0);
  text[0] := Str.Split("Hoy es el di­a mas hermoso de nuestra vida, querido Sancho;", ' ');
  text[1] := Str.Split("los obstaculos mas grandes, nuestras propias indecisiones;", ' ');
  text[2] := Str.Split("nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;", ' ');
  text[3] := Str.Split("la cosa mas facil, equivocarnos;", ' ');
  text[4] := Str.Split("la mas destructiva, la mentira y el egoi­smo;", ' ');
  text[5] := Str.Split("la peor derrota, el desaliento;", ' ');
  text[6] := Str.Split("los defectos mas peligrosos, la soberbia y el rencor;", ' ');
  text[7] := Str.Split("las sensaciones mas gratas, la buena conciencia...", ' ');

  PrintJaggedArray(text);
  UpperCaseRandomArray(text); 
  PrintJaggedArray(text); 
  GraphJaggedArray(text);

  (* Array Exceptions *)

  PrintTitle("Common Array Exceptions"); 

  PrintCommonArrayExceptions(nil); 
  PrintCommonArrayExceptions(text);  

  (* Accessing Class Array Elements through Indexer *) 

  PrintTitle("Alphabets"); 

  vowels := new Alphabet(5,nil,nil); 
  vowels[0] := char('a'); 
  vowels[1] := char('e'); 
  vowels[2] := char('i'); 
  vowels[3] := char('o'); 
  vowels[4] := char('u');

  vs := new ArrayOfChar(5);
  vs[0] := vowels[0]; vs[1] := vowels[1]; 
  vs[2] := vowels[2]; vs[3] := vowels[3]; 
  vs[4] := vowels[4];
  
  writeln;
  writeln("Vowels = {":0, Str.Join(',', vs):0, "}":0);

  en := new Alphabet(0,'abcdefghijklmnopqrstuvwxyz',nil);
  writeln("English Alphabet = {":0,en.ToString(),"}":0);  
  
  na := new Alphabet(0,nil,en.Slice(9, 19));
  writeln("Alphabet Extract en[9..19] = {":0,na.ToString():0,"}":0);             

  w := new ArrayOfChar(5); 
  w[0] := en[6]; w[1] := en[14]; w[2] := en[14]; w[3] := en[3];
  copy(w, word1);

  w := new ArrayOfChar(4); 
  w[0] := en[1]; w[1] := en[24]; w[2] := en[4];
  copy(w, word2);
  
  w := new ArrayOfChar(9); 
  w[0] := en[4]; w[1] := en[21]; w[2] := en[4]; w[3] := en[17]; 
  w[4] := en[24]; w[5] := en[14]; w[6] := en[13]; w[7] := en[4];
  copy(w, word3);

  writeln;
  writeln(word1:0, " ":0, word2:0, ", ":0, word3:0, "!":0); 
  writeln;

  readln; 
end Main.


The output:






















































































Voilà, that's it. Next post in the following days.

Tuesday, November 19, 2013

Arrays and Indexers in Cobra



Today's post is about Arrays and Indexers in Cobra. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Cobra, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


use System.Text

namespace CobraArrays

class Program is public
    shared   
        def main
            # Single-dimensional Array(s)  
            .printTitle("Reverse Array Elements")
            
            # Declare and initialize Array of Chars 
            letters as char[] = char[](5)
            letters[0] = c'A'  
            letters[1] = c'E'  
            letters[2] = c'I'  
            letters[3] = c'O'  
            letters[4] = c'U'
            
            .printArrayChar(letters)  
            inverse_letters as char[] = .reverseChar(letters)  
            .printArrayChar(inverse_letters)
        
            .printTitle("Sort Integer Array Elements")  

            # Declare and Initialize Array of Integers  
            numbers as int[] = @[10, 8, 3, 1, 5]
            .printArrayInt(numbers)  
            ordered_numbers as int[] = .bubblesortInt(numbers)  
            .printArrayInt(ordered_numbers)  

            .printTitle("Sort String Array Elements")  

            # Declare and Initialize and Array of Strings  
            names as String[] = @[   
                'Damian', 
                'Rogelio',   
                'Carlos', 
                'Luis', 
                'Daniel'  
            ]  
            .printArrayString(names)  
            ordered_names as String[] = .bubblesortString(names)  
            .printArrayString(ordered_names)  

            # Multi-dimensional Array (Matrix row,column) 
            # Cobra does not support multi-dimensional arrays syntax            
            # using List<of List<of Type>> instead
            .printTitle("Transpose Matrix")  

            /# Matrix row=2,col=3   
            # A =  [6  4 24]   
            #      [1 -9  8]   
            #/               
            matrix as List<of List<of int>> = [[6, 4, 24],
                                                [1, -9, 8]]            

            .printMatrix(matrix)  
            transposed_matrix as List<of List<of int>> = .transposeMatrix(matrix)  
            .printMatrix(transposed_matrix)  
        
            # Jagged Array (Array-of-Arrays)  
            .printTitle("Upper Case Random Array & Graph Number of Elements")  

            /#               
            # Creating an array of string arrays using the String.Split method  
            # instead of initializing it manually as follows:  
            #   
            # text as String[] = @[   
            #      @[ 'word1', 'word2', 'wordN' ],   
            #      @[ 'word1', 'word2', 'wordM' ],   
            #      ...  
            #      ]  
            #   
            # Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"  
            #   
            #/  
            text = [ _
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(c' '),   
            "los obstáculos más grandes, nuestras propias indecisiones;".split(c' '),
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(c' '),
            "la cosa más fácil, equivocarnos;".split(c' '),
            "la más destructiva, la mentira y el egoísmo;".split(c' '),
            "la peor derrota, el desaliento;".split(c' '),
            "los defectos más peligrosos, la soberbia y el rencor;".split(c' '),
            "las sensaciones más gratas, la buena conciencia...".split(c' ')
            ]
            
            .printJaggedArray(text)  
            /#
            .uppercaserandomArray(text)  
            #/
            .printJaggedArray(text)  
            .graphJaggedArray(text)  
            
            # Array Exceptions  
            .printTitle("Common Array Exceptions")  

            .printCommonArrayExceptions(nil)  
            .printCommonArrayExceptions(text)  

            # Accessing Class Array Elements through Indexer      
            .printTitle("Alphabets")  
            
            vowels as Alphabet = Alphabet(5)  
            vowels[0] = c'a'  
            vowels[1] = c'e'  
            vowels[2] = c'i'  
            vowels[3] = c'o'  
            vowels[4] = c'u'  

            print "\nVowels = {" + [vowels[0], vowels[1], vowels[2], 
                                vowels[3], vowels[4]].join(",") + "}"  

            en as Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz")  
            print "English Alphabet = {[en.toString]}"  

            print "Alphabet Extract en\[9..19\] = {[Alphabet(en.slice(9, 10))]}"

            word1 as String = [en[6], en[14], en[14], en[3]].join('')  
            word2 as String = [en[1], en[24], en[4]].join('')
            word3 as String = [en[4], en[21], en[4], en[17], en[24],   
                                en[14], en[13], en[4]].join('')
            print "\n[word1] [word2], [word3]!"  

            Console.read
        
        def reverseChar(arr as char[]) as char[]
            reversed as char[] = char[](arr.length)  
            i as int = 0  
            for j in arr.length-1:-1:-1
                reversed[i] = arr[j]  
                i += 1
            return reversed
            
        def bubblesortInt(arr as int[]) as int[]  
            swap as int = 0  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j] > arr[j + 1]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
            
        def bubblesortString(arr as String[]) as String[]
            swap as String = ""  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j][0] > arr[j + 1][0]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
        
        def transposeMatrix(m as List<of List<of int>>) as List<of List<of int>>
            /# Transposing a Matrix 2,3   
            #   
            # A =  [6  4 24]T [ 6  1]   
            #      [1 -9  8]  [ 4 -9]  
            #                 [24  8]  
            #/ 
            transposed = [[0]] # to get [int] instead of [object]
            transposed.clear
            for i in 0:m[0].count
                transposed.add([0]) # same here
                transposed[i].clear
                for j in 0:m.count    
                    transposed[i].add(m[j][i])
            return transposed        
        
        def printArrayChar(arr as char[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
                
        def printArrayInt(arr as int[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printArrayString(arr as String[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printMatrix(m as List<of List<of int>>)
            print "\nPrint Matrix Content " + m.getType.name 
            for i in 0:m.count 
                for j in 0:m[0].count  
                    print " array " + String.format("[[{0,2},{1,2}]] = {2,2} " _ 
                        , i, j, m[i][j])
        
        def graphJaggedArray(arr as List<of String[]?>)  
            /# When using Arrays, we can use for(each) instead of for by index:         
            #    
            # for s in arr: 
            #   for w as String in s 
            #    
            #/  
            print "\nPrint Text Content [arr.getType.name]"  
            for i in arr.count  
                Console.write("Line{0,2}|", i+1)
                for j in arr[i].length  
                    Console.write("{0,3}", "*")
                print " ([arr[i].length.toString])"  
        
        def printJaggedArray(arr as List<of String[]?>)  
            line as StringBuilder?      
            print "\nPrint Jagged Array Content [arr.getType.name]"
            for i in arr.count
                line = StringBuilder() 
                for j in arr[i].length
                    line.append(" " + arr[i][j])
                if line.toString == line.toString.toUpper  
                    line.append(r" <-- [UPPERCASED]")  
                print line.toString
        
        def printCommonArrayExceptions(arr as List<of String[]?>?)  
            try  
                arr[100][100] = "hola"    
            catch ex as Exception      
                print "\nException: \n[ex.getType.name]\n[ex.message]"  
        
        def printTitle(message as String) 
            print ""
            print "======================================================"
            print message
            print "======================================================"
    
class Alphabet is public
    # Array Field
    var _letters as char[]? is private
    
    # Indexer Get/Set Property  
    pro [index as int] as char is public
        get
            return _letters[index]
        set
            _letters[index] = value.toUpper
            
    # Read-Only Property  
    get length as int is public
        return _letters.length
    
    # Constructors
    cue init(size as int) is public  
        base.init  
        _letters = char[](size)
    
    cue init(list as String) is public
        base.init
        _letters = list.toUpper.toCharArray
    
    cue init(list as char[]) is public
        base.init
        _letters = list
    
    # Overridden Method    
    def toString as String is override
        return "" + _letters.join(',')

    # Method 
    def slice(start as int, length as int) as char[]?
        return _letters[start:start+length]


The output:






















































































Voilà, that's it. Next post in the following days.

Sunday, October 27, 2013

Arrays and Indexers in Phalanger



Today's post is about Arrays and Indexers in Phalanger (PHP). Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Phalanger (PHP), in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the first post of a "dynamic" language implemented for the DLR. You will notice that the code structure its slightly different from previous posts. Besides that, because Phalanger is PHP, it is definitely better to use PHP's array type instead of System\Array, implemented in Phalanger as PhpArray which at the end, stores the data as a Dictionary<object,object>.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


<?php
namespace PhpArrays 
{    
    use System as S;
    use System\Console;
    use System\Random;
    use System\Text as T;
    
    class Program
    {
        static function Main()
        {            
            /* 
             * An array in PHP is actually an ordered map.
             * implements arrays as Phpp.Runtime.PhpArray class 
             * that internally implements a Dictionary<object,object>.
            */
            
            // Single-dimensional Array(s)  
            self::printTitle("Reverse Array Elements");
            
            // Declare and Initialize Array of Chars  
            $letters = array();  
            $letters[0] = "A";  
            $letters[1] = "E";  
            $letters[2] = "I";  
            $letters[3] = "O";  
            $letters[4] = "U"; 
            
            //print_r($letters);
            self::printArray($letters);
            $inverse_letters = self::reverseChar($letters);  
            self::printArray($inverse_letters);  
            
            self::printTitle("Sort Integer Array Elements");  
            
            // Declare and Initialize Array of Integers   
            $numbers = array ( 10, 8, 3, 1, 5 );  
            self::printArray($numbers);  
            $ordered_numbers = self::bubbleSort($numbers);  
            self::printArray($ordered_numbers);  
            
            self::printTitle("Sort String Array Elements");  
            
            // Declare and Initialize and Array of Strings  
            $names = array (                       
                    "Damian",   
                    "Rogelio",  
                    "Carlos",   
                    "Luis",                       
                    "Daniel"  
                );  
            self::printArray($names);  
            $ordered_names = self::bubbleSort($names);  
            self::printArray($ordered_names);  
            
            // Multi-dimensional Array (Matrix row,column)  
            // in PHP they are the same as Jagged Arrays or "array of arrays"
            
            self::printTitle("Transpose Matrix");  
            
            /* Matrix row=2,col=3 
             * A =  [6  4 24] 
             *      [1 -9  8] 
             */  
            $matrix = array ( array ( 6, 4, 24 ),   
                              array ( 1, -9, 8 ));  
            self::printMatrix($matrix);  
            $transposed_matrix = self::transposeMatrix($matrix);  
            self::printMatrix($transposed_matrix);  
            
            // Jagged Array (Array-of-Arrays)         
            
            self::printTitle("Upper Case Random Array & Graph Number of Elements");  
            
            /*              
             * Creating an array of string arrays using the String.Split method 
             * instead of initializing it manually as follows: 
             *  
             * $text = array (  
             *      array ( "word1", "word2", "wordN" ),  
             *      array ( "word1", "word2", "wordM" ),  
             *      ... 
             *      ); 
             *  
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
             *  
             */  
            // using php function explode (split also works)
            $text = array (   
            \explode(" ", "Hoy es el día más hermoso de nuestra vida, querido Sancho;"),  
            \explode(" ", "los obstáculos más grandes, nuestras propias indecisiones;"),  
            \explode(" ", "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;"),  
            \explode(" ", "la cosa más fácil, equivocarnos;"),
            \explode(" ", "la más destructiva, la mentira y el egoísmo;"),
            \explode(" ", "la peor derrota, el desaliento;"),
            \explode(" ", "los defectos más peligrosos, la soberbia y el rencor;"),
            \explode(" ", "las sensaciones más gratas, la buena conciencia...")
            );          
            //print_r ($text);
            self::printJaggedArray($text);  
            $text = self::upperCaseRandomArray($text);  // param not by reference
            self::printJaggedArray($text);  
            self::graphJaggedArray($text);  
            
            // Array Exceptions  
            
            self::printTitle("Common Array Exceptions");  
            
            self::printCommonArrayExceptions(NULL);  
            self::printCommonArrayExceptions($text);  
            
            // Accessing Class Array Elements through Indexer  
            
            self::printTitle("Alphabets");  
            
            $vowels = new Alphabet(5);  
            $vowels[0] = 'a';  
            $vowels[1] = 'e';  
            $vowels[2] = 'i';  
            $vowels[3] = 'o';  
            $vowels[4] = 'u';  
            
            //print_r ($vowels);
            
            echo "\nVowels = {" 
                . \implode(",", array($vowels[0], $vowels[1], $vowels[2], $vowels[3], $vowels[4])) 
                . "}\n";                  
            
            $en = new Alphabet("abcdefghijklmnopqrstuvwxyz");  
            echo "English Alphabet = {{$en}}\n";  
  
            echo "Alphabet Extract en[9..19] = {"
                . new Alphabet($en->slice(9, 10))  
                . "}\n";
            
            $word1 = \implode("", array ($en[6], $en[14], $en[14], $en[3]));  
            $word2 = \implode("", array ($en[1], $en[24], $en[4]));  
            $word3 = \implode("", array ($en[4], $en[21], $en[4], $en[17],  
                                         $en[24], $en[14], $en[13], $en[4]));  
  
            echo "\n$word1 $word2, $word3!\n";
  
            \fgets(STDIN);

            return 0;
        }
        
        static function reverseChar($arr)
        {              
            $reversed = array();  
            for ($i = 0, $j = \count($arr) - 1; $j >= 0; $i++, $j--)  
            {
                $reversed[$i] = $arr[$j]; 
            }
            return $reversed;  
            // or: return \array_reverse($arr);
        }  
        
        static function bubbleSort($arr)  
        {  
            $swap = 0;  
            for ($i = \count($arr) - 1; $i > 0; $i--)  
            {  
                for ($j = 0; $j < $i; $j++)  
                {  
                    // if ($arr[$j][0] > $arr[$j + 1][0])  
                    if (\is_numeric($arr[$j]) ? 
                        $arr[$j] > $arr[$j + 1] : 
                        $arr[$j][0] > $arr[$j + 1][0])  
                    {  
                        $swap = $arr[$j];  
                        $arr[$j] = $arr[$j + 1];  
                        $arr[$j + 1] = $swap;  
                    }  
                }  
            }  
            return $arr;  
        }  
                                    
        static function transposeMatrix($m)  
        {  
            /* Transposing a Matrix 2,3  
             *  
             * A =  [6  4 24]T [ 6  1]  
             *      [1 -9  8]  [ 4 -9] 
             *                 [24  8] 
             */
            $transposed = array();  
            for ($i = 0; $i < \count($m); $i++)  
            {  
                for ($j = 0; $j < \count($m[0]); $j++)  
                {  
                    $transposed[$j][$i] = $m[$i][$j];                  
                }  
            }  
            return $transposed;  
        }  
        
        static function upperCaseRandomArray($arr)  
        {  
            $r = new Random();  
            $i = $r->Next(0, \count($arr) - 1);  
            for ($j = 0; $j < \count($arr[$i]); $j++)  
            {
                $arr[$i][$j] = \strtoupper($arr[$i][$j]);  
            }
            return $arr;
        }  
        
        static function printArray($arr)  
        {  
            echo "\nPrint Array Content " . $arr->GetType()->Name . "\n";
            
            for ($i = 0; $i < \count($arr); $i++)  
            {
                Console::WriteLine(" array [{0,2}] = {1,2} ", $i, $arr[$i]);          
            }
        }  
        
        static function printMatrix($m)  
        {  
            echo "\nPrint Matrix Content " . $m->GetType()->Name 
            . "[" . \count($m) . "," . \count($m[0]) . "]\n";        
            
            for ($i = 0; $i < \count($m); $i++)  
            {
                for ($j = 0; $j < \count($m[0]); $j++)  
                {
                    Console::WriteLine(" array [{0,2},{1,2}] = {2,2} ", $i, $j, $m[$i][$j]);  
                }
            }
        }  
        
        static function graphJaggedArray($arr)  
        {  
            /* When using Arrays, we can use foreach instead of for:  
             *  
             * for (int i = 0; i <= arr.Length - 1; i++) 
             *   for (int j = 0; j <= arr.Length - 1; j++)                 
             *  
             */  
            echo "\nPrint Text Content " . $arr->GetType()->Name . "\n";  
            $lineCount = 1;  
            foreach ($arr as $s)  
            {  
                Console::Write("Line{0,2}|", $lineCount);  
                foreach ($s as $w)  
                {  
                    Console::Write("{0,3}", '*');  
                }  
                echo " (" . \count($s) . ")\n";  
                $lineCount++;  
            }  
        }  
        
        static function printJaggedArray($arr)  
        {          
            echo "\nPrint Jagged Array Content " . $arr->GetType()->Name . "\n";  
            for ($i = 0; $i < \count($arr); $i++)  
            {  
                $line = new T\StringBuilder();  
                for ($j = 0; $j < \count($arr[$i]); $j++)
                {
                    $line->Append(" " . $arr[$i][$j]);  
                }
                if ($line->ToString() == \strtoupper($line->ToString()))  
                {
                    $line->Append(" <-- [UPPERCASED]");  
                }
                echo $line . "\n";  
            }  
        }  

        static function printCommonArrayExceptions($arr)  
        {  
            // there is a bug throwing System\Exception(s) in Phalanger.
            // but apparently it has been quickly fixed after reported.
            try  
            {  
                /* Throwing System\Exception(s) do not get caught in
                 * the catch, instead they give an error message and 
                 * continue executing. i.e.
                 * throw new S\NullReferenceException("");                    
                 * throw new S\Exception("");
                */
                
                if (\is_null($arr))
                {
                    throw new \ErrorException(
                        "Object reference not set to an instance of an object.", 
                        0, \E_ERROR);                    
                }
                if (!isset($arr[100][100]))
                {
                    throw new \OutOfRangeException(
                        "Index was outside the bounds of the array.", 0);
                }      
            }  
            catch (\OutOfRangeException $ex)  
            {  
                echo "\nException: OutOfRangeException\n" . 
                    $ex->getMessage() . "\n";  
            } 
            catch (\ErrorException $ex)  
            {  
                echo "\nException: ErrorException " .
                    $ex->getSeverity() . "\n" . $ex->getMessage() . "\n";                
            }             
            /*catch (S\Exception $ex)
            {
                echo "\nException: ", "Exception", 
                    $ex->getMessage(), "\n";  
            }*/
        }  
        
        static function printTitle(string $message)
        {
            echo "\n";
            echo \str_repeat("=", 54) . "\n";
            echo $message . "\n";
            echo \str_repeat("=", 54) . "\n";
        }
    }

    [\Export]    
    class Alphabet implements \ArrayAccess   
    {    
        // Array Field
        private $letters = array();
        
        // Indexer Get/Set methods
        // Implementing ArrayAccess methods
        public function offsetSet($offset, $value) {
            if (\is_null($offset)) 
            {
                $this->letters[] = $value;
            } else 
            {
                $this->letters[$offset] = \strtoupper($value);
            }
        }
        public function offsetExists($offset) {
            return isset($this->letters[$offset]);
        }
        public function offsetUnset($offset) {
            unset($this->letters[$offset]);
        }
        public function offsetGet($offset) {
            return isset($this->letters[$offset]) ? $this->letters[$offset] : NULL;
        }
        
        // Read-Only Property  
        public function getLength()
        {  
            return \count($this->letters); 
        }  
        
        // Constructor 
        // No Overloaded Constructors support in (PHP) Phalanger 
        public function __construct($param = NULL)    
        {   
            // int $size
            if(\is_numeric($param))
            {
                $this->letters = \array_pad($this->letters, $size, ' '); 
            }
            // string $list
            else if(\is_string($param))
            {
                $this->letters = \str_split(\strtoupper($param));
            }
            // array $list
            else if(\is_array($param))
            {
                $this->letters = $param;
            }
            else 
            {
                $this->letters = NULL;
            }
        }    
        
        // Overridden Method
        public function __toString()    
        {    
            return \join(",", $this->letters); 
        }
        
        // Method  
        public function slice($start, $length)  
        {  
            return \array_slice($this->letters, $start, $length);              
        }  
    }    
}
?>


The output:






















































































Voilà, that's it. Next post in the following days.

Tuesday, October 22, 2013

Arrays and Indexers in Nemerle



Today's post is about Arrays and Indexers in Nemerle. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Nemerle, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in C# and C++ just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


using Nemerle.IO;
using System;
using System.Console;
using System.Text;

namespace NsArrays
{  
    module Program
    {
        Main() : void
        {
            // Single-dimensional Array(s)  
            PrintTitle("Reverse Array Elements");  
            
            // Declare and Initialize Array of Chars  
            def letters : array[char] = array(5);  
            letters[0] = 'A';  
            letters[1] = 'E';  
            letters[2] = 'I';  
            letters[3] = 'O';  
            letters[4] = 'U';  
            
            PrintArrayChar(letters); 
            def inverse_letters : array[char] = ReverseChar(letters);  
            PrintArrayChar(inverse_letters);  
            
            PrintTitle("Sort Integer Array Elements");  
  
            // Declare and Initialize Array of Integers   
            def numbers : array[int] = array [10, 8, 3, 1, 5];
            PrintArrayInt(numbers);
            def ordered_numbers : array[int] = BubbleSortInt(numbers);  
            PrintArrayInt(ordered_numbers);  
  
            PrintTitle("Sort String Array Elements");  
  
            // Declare and Initialize and Array of Strings   
            def names : array[string] = array[
                    "Damian",   
                    "Rogelio",  
                    "Carlos",   
                    "Luis",                       
                    "Daniel"  
                ];
            
            PrintArrayString(names);  
            def ordered_names : array[string] = BubbleSortString(names);  
            PrintArrayString(ordered_names);  
  
            // Multi-dimensional Array (Matrix row,column)  
  
            PrintTitle("Transpose Matrix");  
  
            /* Matrix row=2,col=3 
             * A =  [6  4 24] 
             *      [1 -9  8] 
            */
            def matrix : array[2,int] = array.[2][[ 6, 4, 24 ],   
                                                  [ 1, -9, 8 ]];
            
            PrintMatrix(matrix);  
            def transposed_matrix : array[2,int] = TransposeMatrix(matrix);  
            PrintMatrix(transposed_matrix);
            
            // Jagged Array (Array-of-Arrays)  
  
            PrintTitle("Upper Case Random Array & Graph Number of Elements");  
  
            /*              
             * Creating an array of string arrays using the String.Split method 
             * instead of initializing it manually as follows: 
             *  
             * def text : array[array[string]] = array[ 
             *      array[ "word1", "word2", "wordN" ],  
             *      array[ "word1", "word2", "wordM" ],  
             *      ... 
             *      ]; 
             *  
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha" 
             *  
             */           
            def text : array[array[string]] = array[   
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".Split(' '),  
            "los obstáculos más grandes, nuestras propias indecisiones;".Split(' '),  
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".Split(' '),  
            "la cosa más fácil, equivocarnos;".Split(' '),  
            "la más destructiva, la mentira y el egoísmo;".Split(' '),  
            "la peor derrota, el desaliento;".Split(' '),  
            "los defectos más peligrosos, la soberbia y el rencor;".Split(' '),  
            "las sensaciones más gratas, la buena conciencia...".Split(' ')
            ];  
            PrintJaggedArray(text);  
            UpperCaseRandomArray(text);  
            PrintJaggedArray(text);  
            GraphJaggedArray(text);  
            
            // Array Exceptions  
  
            PrintTitle("Common Array Exceptions");  
            
            PrintCommonArrayExceptions(null);  
            PrintCommonArrayExceptions(text);  
  
            // Accessing Class Array Elements through Indexer  
  
            PrintTitle("Alphabets");  
  
            def vowels : Alphabet = Alphabet(5);  
            vowels[0] = 'a';  
            vowels[1] = 'e';  
            vowels[2] = 'i';  
            vowels[3] = 'o';  
            vowels[4] = 'u';  
  
            printf("\nVowels = {%s}\n",  
                String.Join(",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));  
  
            def en : Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz");  
            printf("English Alphabet = {%s}\n", en.ToString());  
  
            printf("Alphabet Extract en[9..19] = {%s}\n",   
                          Alphabet(en.Slice(9, 10)).ToString());  
  
            def word1 : string = String.Join("", en[6], en[14], en[14], en[3]);  
            def word2 : string = String.Join("", en[1], en[24], en[4]);  
            def word3 : string = String.Join("", en[4], en[21], en[4], en[17],  
                                           en[24], en[14], en[13], en[4]);  
  
            printf("\n%s %s, %s!\n\n", word1, word2, word3);  
                                                  
            _ = ReadLine();
        }
        
        ReverseChar(arr : array[char]) : array[char]
        {
            def reversed : array[char] = array(arr.Length);
            mutable i : int = 0;
            for (mutable j : int = arr.Length - 1; j >= 0; j--)  
            {
                reversed[i] = arr[j];
                i++;
            }
            reversed;
        }
        
        BubbleSortInt(arr : array[int]) : array[int]
        {
            mutable swap : int = 0;
            for (mutable i : int = arr.Length - 1; i > 0; i--)
            {
                for (mutable j: int = 0; j < i; j++)
                {                    
                    if (arr[j] > arr[j + 1])  
                    { 
                        swap = arr[j];  
                        arr[j] = arr[j + 1];
                        arr[j + 1] = swap;
                    }
                    else{}
                }
            }
            arr;
        }

        BubbleSortString(arr : array[string]) : array[string]
        {
            mutable swap : string = "";
            for (mutable i : int = arr.Length - 1; i > 0; i--)
            {
                for (mutable j: int = 0; j < i; j++)
                {
                    if (arr[j][0] > arr[j + 1][0]) 
                    {
                        swap = arr[j];  
                        arr[j] = arr[j + 1];  
                        arr[j + 1] = swap;
                    }
                    else{}
                }
            }
            arr;
        }
        
        TransposeMatrix(m : array[2, int]) : array[2, int]
        {  
            /* Transposing a Matrix 2,3  
             *  
             * A =  [6  4 24]T [ 6  1]  
             *      [1 -9  8]  [ 4 -9] 
             *                 [24  8] 
            */  
            def transposed : array[2, int] = array(m.GetUpperBound(1) + 1,  
                                                   m.GetUpperBound(0) + 1);  
            for (mutable i : int = 0; i < m.GetUpperBound(0) + 1; i++)  
            {  
                for (mutable j = 0; j < m.GetUpperBound(1) + 1; j++)  
                {  
                    transposed[j, i] = m[i, j];  
                }  
            }  
            transposed;  
        }  
        
        UpperCaseRandomArray(arr : array[array[string]]) : void
        {  
            def r : Random = Random();  
            mutable i : int = r.Next(0, arr.Length - 1);  
            for (mutable j : int = 0; j <= arr[i].Length - 1; j++)  
                arr[i][j] = arr[i][j].ToUpper();  
        }  
        
        PrintArrayChar(arr : array[char]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        }  
        
        PrintArrayInt(arr : array[int]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        } 
        
        PrintArrayString(arr : array[string]) : void  
        {
            printf("\nPrint Array Content %s\n", 
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));  
              
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
                WriteLine("  array [{0,2}] = {1,2} ", i, arr[i]);
        } 
        
        PrintMatrix(m : array[2,int]) : void  
        {  
            printf("\nPrint Matrix Content %s[%s,%s]\n",  
                m.GetType().Name.Replace("[,]", ""),  
                (m.GetUpperBound(0) + 1).ToString(),  
                (m.GetUpperBound(1) + 1).ToString());  
  
            for (mutable i : int = 0; i <= m.GetUpperBound(0); i++)  
                for (mutable j : int = 0; j <= m.GetUpperBound(1); j++)  
                    WriteLine(" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);  
        }  
        
        GraphJaggedArray(arr : array[array[string]]) : void  
        {  
            /* When using Arrays, we can use foreach instead of for:  
             *  
             * for (mutable i : int = 0; i <= arr.Length - 1; i++) 
             *   for (mutable j : int = 0; j <= arr.Length - 1; j++)                 
             *  
            */  
            printf("\nPrint Text Content %s\n", arr.GetType().Name);  
            mutable lineCount : int = 1;  
            foreach (s : array[string] in arr)  
            {  
                Write("Line{0,2}|", lineCount);  
                foreach (_ : string in s)  
                {  
                    Write("{0,3}", '*');  
                }  
                printf(" (%s)\n", s.Length.ToString());  
                lineCount++;  
            }  
        }  
        
        PrintJaggedArray(arr : array[array[string]]) : void  
        {  
            mutable line : StringBuilder;  
            printf("\nPrint Jagged Array Content %s\n", arr.GetType().Name);  
            for (mutable i : int = 0; i <= arr.Length - 1; i++)  
            {  
                line = StringBuilder();  
                for (mutable j : int = 0; j <= arr[i].Length - 1; j++)  
                    _ = line.Append(" " + arr[i][j]);  
                if (line.ToString() == line.ToString().ToUpper()) 
                {
                    _ = line.Append(" <-- [UPPERCASED]");  
                }
                else {}
                printf("%s\n", line.ToString());  
            }  
        }  
        
        PrintCommonArrayExceptions(arr : array[array[string]]) : void
        {  
            try  
            {  
                arr[100][100] = "hola";  
            }  
            catch             
            {  
            | ex is Exception =>
                printf("\nException: \n%s\n%s\n", ex.GetType().Name, ex.Message);  
            }  
        }  
                
        PrintTitle(message : string) : void
        {
            print("\n");
            print("======================================================\n");
            printf("%s\n", message);  
            print("======================================================\n");  
        }
    }
    
    class Alphabet  
    {  
        // Array Field  
        private letters : array[char];  
  
        // Indexer Get/Set Property  
        public Item[index : int] : char
        {  
            get { letters[index] }  
            set { letters[index] = Char.ToUpper(value) }  
        }  

        // Read-Only Property  
        public Length : int
        {  
            get { this.letters.Length }  
        }  
  
        // Constructors  
        public this(size : int)  
        {  
            this.letters = array(size); 
        }  
  
        public this(lst : string)  
        {  
            this.letters = lst.ToUpper().ToCharArray();  
        }  
  
        public this(lst : array[char])  
        {  
            this.letters = lst;
        }  
  
        // Overridden Method  
        public override ToString() : string
        {  
            String.Join(",", this.letters); 
        }  
  
        // Method  
        public Slice(start : int, length : int) : array[char]
        {  
            def result : array[char] = array(length);  
            mutable j : int = start;
            for (mutable i : int = 0; i < length; i++)  
            {  
                result[i] = this[j];  
                j++;
            }  
            result;
        }  
  
    }  
}


The output:






















































































Voilà, that's it. Next post in the following days.