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.

No comments:

Post a Comment