Showing posts with label Nemerle. Show all posts
Showing posts with label Nemerle. Show all posts

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.

Sunday, March 27, 2011

Factorial and Fibonacci in Nemerle



Here below a little program in Nemerle that implements 2 classes (in fact, they are 3). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in Nemerle
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using Nemerle.IO;

namespace FiborialN
{
    // Module = Static Class
    // all members become static by default
    // no need to explicitly use static on members (i did anyway)
    module StaticFiborial
    {
        // Static Field
        static mutable className : string; 
        // Static Constructor
        static this()
        {
            className = "Static Constructor";
            printf("%s", className);
        }
        // Static Method - Factorial Recursive
        public static FactorialR(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialR(n - 1);
        }
        // Static Method - Factorial Imperative
        public static FactorialI(n : int) : BigInteger
        {
            mutable res : BigInteger = BigInteger(1);
            for (mutable i : int = n; i >= 1; i--)
                res *= i;
            res;
        }
        // Static Method - Fibonacci Recursive
        public static FibonacciR(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                FibonacciR(n - 1) + FibonacciR(n - 2);
        }
        // Static Method - Fibonacci Imperative
        public static FibonacciI(n : int) : long
        {            
            mutable pre : long = 1;
            mutable cur : long = 1;
            mutable tmp : long = 0;
            
            for (mutable i : int = 2; i <= n; i++)
            {
                tmp = cur + pre;
                pre = cur;
                cur = tmp;
            }
            cur;
        }
        // Static Method - Benchmarking Algorithms
        public static BenchmarkAlgorithm(algorithm : int, values : list[int]) : void
        {            
            def timer : Stopwatch = Stopwatch();
            mutable i : int = 0;
            mutable testValue : int = 0;
            mutable facTimeResult : BigInteger = BigInteger(0);
            mutable fibTimeResult : long = 0;
           
            // "Switch" Flow Constrol Statement
            match (algorithm)
            {
                | 1 =>
                    printf("\nFactorial Imperative:\n");
                    // "For" Loop Statement
                    for (i = 0; i < values.Length; i++)
                    {
                        testValue = values.Nth(i);
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialI(testValue);
                        timer.Stop();                        
                        // Getting Time
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }
                | 2 =>
                    printf("\nFactorial Recursive:\n");
                    // 'While' Loop Statement  
                    while (i < values.Length) 
                    {
                        testValue = values.Nth(i);  
                        // Taking Time  
                        timer.Start();  
                        facTimeResult = FactorialR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;
                    }
                | 3 =>
                    printf("\nFibonacci Imperative:\n");
                    // 'Do-While' Loop Statement  
                    do {  
                        testValue = values.Nth(i);  
                        // Taking Time 
                        timer.Start();  
                        fibTimeResult = FibonacciI(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                        i++;  
                    } while (i < values.Length);  
                | 4 =>
                    printf("\nFibonacci Recursive:\n");
                    // 'For Each' Loop Statement  
                    foreach (item : int in values) {  
                        testValue = item;
                        // Taking Time  
                        timer.Start();  
                        fibTimeResult = FibonacciR(testValue);  
                        timer.Stop();  
                        // Getting Time  
                        printf(" (%d) = %s\n", testValue, timer.Elapsed.ToString());
                    }  
                | _ => printf("DONG!");
            }                
        }
    }
    
    // Instance Class  
    public class InstanceFiborial 
    {  
        // Instance Field  
        mutable className : String;  
        // Instance Constructor  
        public this() 
        {  
            this.className = "Instance Constructor";  
            printf("%s", this.className);
        }  
        // Instance Method - Factorial Recursive  
        public FactorialR(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FactorialI(n : int) : BigInteger 
        {  
            // Calling Static Method  
            StaticFiborial.FactorialI(n);  
        }  
        // Instance Method - Fibonacci Recursive  
        public FibonacciR(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciR(n);  
        }  
        // Instance Method - Factorial Imperative  
        public FibonacciI(n : int) : long 
        {  
            // Calling Static Method  
            StaticFiborial.FibonacciI(n);  
        }  
    }  
    
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Calling Static Class and Methods  
            // No instantiation needed. Calling method directly from the class 
            printf("FacImp(5) = %s\n", StaticFiborial.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", StaticFiborial.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", StaticFiborial.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", StaticFiborial.FibonacciR(11).ToString());  

            printf("\nInstance Class\n");  
            // Calling Instance Class and Methods   
            // Need to instantiate before using. Calling method from instantiated object  
            def ff : InstanceFiborial = InstanceFiborial();  
            printf("FacImp(5) = %s\n", ff.FactorialI(5).ToString());  
            printf("FacRec(5) = %s\n", ff.FactorialR(5).ToString());  
            printf("FibImp(11)= %s\n", ff.FibonacciI(11).ToString());  
            printf("FibRec(11)= %s\n", ff.FibonacciR(11).ToString()); 

            // Create a (nemerle) list of integer values to test
            // From 5 to 50 by 5
            mutable values : list[int] = [];
            foreach (i in $[5,10..50])
                values ::= i;
                    
            // Benchmarking Fibonacci                       
            // 1 = Factorial Imperative              
            StaticFiborial.BenchmarkAlgorithm(1, values.Reverse());
            // 2 = Factorial Recursive  
            StaticFiborial.BenchmarkAlgorithm(2, values.Reverse());

            // Benchmarking Factorial              
            // 3 = Fibonacci Imperative  
            StaticFiborial.BenchmarkAlgorithm(3, values.Reverse());
            // 4 = Fibonacci Recursive  
            StaticFiborial.BenchmarkAlgorithm(4, values.Reverse());        

            // Stop and Exit 
            _ = Console.ReadLine();
        }
    }
}

And the Output is:






































Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

Printing the Factorial and Fibonacci Series
using System;  
using System.Text;  
using System.Numerics;
using Nemerle.IO;

namespace FiborialSeries
{
    static class Fiborial
    {
        // Using a StringBuilder as a list of string elements  
        public static GetFactorialSeries(n : int) : string
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = StringBuilder();  
            // We begin by concatenating the number you want to calculate  
            // in the following format: "!# ="  
            _ = series.Append("!");
            _ = series.Append(n);  
            _ = series.Append(" = ");  
            // We iterate backwards through the elements of the series  
            for (mutable i : int = n; i <= n && i > 0; i--)  
            {  
                // and append it to the list  
                _ = series.Append(i);  
                if (i > 1)  
                    _ = series.Append(" * ");  
                else   
                    _ = series.Append(" = ");   
            }  
            // Get the result from the Factorial Method  
            // and append it to the end of the list  
            _ = series.Append(Factorial(n));  
            // return the list as a string  
            series.ToString();  
        }
        // Using a StringBuilder as a list of string elements  
        public static GetFibonnaciSeries(n : int) : string 
        {  
            // Create the String that will hold the list  
            def series : StringBuilder = StringBuilder();  
            // We begin by concatenating the first 3 values which  
            // are always constant  
            _ = series.Append("0, 1, 1");  
            // Then we calculate the Fibonacci of each element  
            // and add append it to the list  
            for (mutable i : int = 2; i <= n; i++)  
            {  
                if (i < n)  
                    _ = series.Append(", ");  
                else  
                    _ = series.Append(" = ");  
                  
                _ = series.Append(Fibonacci(i));  
            }  
            // return the list as a string  
            series.ToString();  
        }  
        // Static Method - Factorial Recursive
        public static Factorial(n : int) : BigInteger
        {            
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * Factorial(n - 1);
        }        
        // Static Method - Fibonacci Recursive
        public static Fibonacci(n : int) : long
        {
            def oneLong : long = 1;
            if (n < 2)
                oneLong;
            else
                Fibonacci(n - 1) + Fibonacci(n - 2);
        }        
    }
        
    module Program
    {
        Main() : void
        {          
            printf("\nStatic Class\n");
            // Printing Factorial Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFactorialSeries(5));
            printf("%s\n", Fiborial.GetFactorialSeries(7));  
            printf("%s\n", Fiborial.GetFactorialSeries(9));  
            printf("%s\n", Fiborial.GetFactorialSeries(11));  
            printf("%s\n", Fiborial.GetFactorialSeries(40));  
            // Printing Fibonacci Series  
            printf("\n");
            printf("%s\n", Fiborial.GetFibonnaciSeries(5));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(7));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(9));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(11));  
            printf("%s\n", Fiborial.GetFibonnaciSeries(40));              
        }
    }
}

And the Output is:



















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the class is marked as static because of the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

using System;  
namespace FiborialExtrasN2
{
    // Instance Class
    class Fiborial  
    {  
        // Instance Field  
        mutable instanceCount : int;  
        // Static Field  
        static mutable staticCount : int;          
        // Instance Read-Only Property  
        // Within instance members, you can always use    
        // the "this" reference pointer to access your (instance) members.  
        public InstanceCount : int
        {  
            get { this.instanceCount; }  
        }  
        // Static Read-Only Property  
        // Remeber that Properties are Methods to the CLR, so, you can also  
        // define static properties for static fields.   
        // As with Static Methods, you cannot reference your class members  
        // with the "this" reference pointer since static members are not  
        // instantiated.          
        public static StaticCount : int
        {  
            get { staticCount; }  
        }  
        // Instance Constructor  
        public this()  
        {  
            this.instanceCount = 0;  
            Console.WriteLine("\nInstance Constructor {0}", this.instanceCount);  
        }  
        // Static Constructor  
        static this()  
        {  
            staticCount = 0;  
            Console.WriteLine("\nStatic Constructor {0}", staticCount);  
        }  
  
        // Instance Method  
        public Factorial(n : int) : void
        {  
            this.instanceCount += 1;  
            Console.WriteLine("\nFactorial({0})", n);  
        }  
  
        // Static Method  
        public static Fibonacci(n : int) : void
        {  
            staticCount += 1;  
            Console.WriteLine("\nFibonacci({0})", n);  
        }                   
    }
        
    module Program
    {
        Main() : void
        {          
            // Calling Static Constructor and Methods  
            // No need to instantiate  
            Fiborial.Fibonacci(5);              
  
            // Calling Instance Constructor and Methods  
            // Instance required  
            def fib : Fiborial = Fiborial();  
            fib.Factorial(5);              
  
            Fiborial.Fibonacci(15);              
            fib.Factorial(5);  
  
            // Calling Instance Constructor and Methods  
            // for a second object  
            def fib2 : Fiborial = Fiborial();  
            fib2.Factorial(5);  
              
            Console.WriteLine();  
            // Calling Static Property  
            Console.WriteLine("Static Count = {0}", Fiborial.StaticCount);  
            // Calling Instance Property of object 1 and 2  
            Console.WriteLine("Instance 1 Count = {0}", fib.InstanceCount);  
            Console.WriteLine("Instance 2 Count = {0}", fib2.InstanceCount); 
        }
    }
}

And the Output is:






















Factorial using System.Int64, System.Double, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just "tried" to say, lets have a look at the following code and the output we get.

#pragma indent
using System;  
using System.Numerics;  
using System.Diagnostics;  
using System.Console;

namespace FiborialExtrasCs3

    module Program
        // Long Factorial
        public static FactorialInt64(n : int) : long
            def oneLong : long = 1;
            if (n == 1)
                 oneLong;
            else 
                 n * FactorialInt64(n - 1);

        // Double Factorial
        public static FactorialDouble(n : int) : double
            def oneDouble : double = 1;
            if (n == 1)
                oneDouble;
            else 
                 n * FactorialDouble(n - 1);

        // BigInteger Factorial
        public static FactorialBigInteger(n : int) : BigInteger
            if (n == 1)
                 BigInteger(1);
            else 
                 BigInteger(n) * FactorialBigInteger(n - 1);
    
        Main() : void
            def timer : Stopwatch = Stopwatch();  
            mutable facIntResult : long = 0;  
            mutable facDblResult : double = 0;  
            mutable facBigResult : BigInteger = BigInteger(0);
                        
            WriteLine("\nFactorial using Int64");
            // Benchmark Factorial using Int64
            // Overflow Exception!!!
            try
                foreach (i in $[5,10..50])
                    timer.Start();  
                    facIntResult = FactorialInt64(i);  
                    timer.Stop();
                    WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facIntResult);  
            catch
                | ex is OverflowException =>
                    // yummy ^_^  
                    WriteLine("Oops! {0}", ex.Message);
            
            WriteLine("\nFactorial using Double");  
            // Benchmark Factorial using Double  
            foreach (i in $[5,10..50])
                timer.Start();  
                facDblResult = FactorialDouble(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facDblResult);  
            
            WriteLine("\nFactorial using BigInteger");  
            // Benchmark Factorial using BigInteger
            foreach (i in $[5,10..50])
                timer.Start();
                facBigResult = FactorialBigInteger(i);
                timer.Stop();
                WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facBigResult);

NOTE: you need to manually add a reference to the System.Numerics.dll assembly to your project so you can add it to your code.

And the Output is:

Saturday, September 25, 2010

Nemerle - Basics by Example



Continue with the Basics by Example; today's version of the post written in Nemerle Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Nemerle Basics
using System;
namespace NGreetProgram
{
    // Greeting Class
    internal class Greet 
    {
        // Fields or Attributes
        private mutable message : string;
        private mutable name : string;
        private mutable loopMessage : int;
        // Properties
        public Message : string 
        {
            get { this.message; }
            set { this.message = this.Capitalize(value); }
        }
        public Name : string {
            get { this.name; }
            set { this.name = this.Capitalize(value); }
        }
        public LoopMessage : int {
            get { this.loopMessage; }
            set { this.loopMessage = value; }
        }
        // Constructor
        public this() {
            this.message = "";
            this.name = "";
            this.loopMessage = 0;
        }
        // Overloaded Constructor
        public this(message : string, name : string, loopMessage : int) 
        {
            this.message = message;
            this.name = name;
            this.loopMessage = loopMessage;
        }
        // Method 1
        private Capitalize(val : string): string 
        {
            if (val.Length >= 1) {
                val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1);
            }
            else {
                "";
            }
        }
        // Method 2
        public Salute() : void
        {
            // "for" statement
            for (mutable i : int = 0; i < this.loopMessage; i++) {
                Console.WriteLine("{0} {1}!", this.message, this.name);                
            }
        }
        // Overloaded Method 2.1
        public Salute(message : string, name : string, loopMessage : int) : void 
        {
            // "while" statement
            mutable i : int = 0;
            while(i < loopMessage) {
                Console.WriteLine("{0} {1}!", this.Capitalize(message), 
                                    this.Capitalize(name));                
                i++;
            }
        }
        // Overloaded Method 2.2
        public Salute(name : string) : void
        {
            // "switch/case" statement is not supported
            // using match statement instead
            def dtNow : DateTime = DateTime.Now;            
            match (dtNow.Hour) {
                |6|7|8|9|10|11 => this.message = "good morning,";
                |12|13|14|15|16|17 => this.message = "good afternoon,";
                |18|19|20|21|22 => this.message = "good evening,";
                |23|0|1|2|3|4|5 => this.message = "good night,";
                | _ => this.message = "huh?"
            }            
            Console.WriteLine("{0} {1}!", this.Capitalize(this.message), 
                                    this.Capitalize(name));
        }
    }

    // Console Program
    public module Program
    {
        public static Main() : void
        {
            // Define object of type Greet
            mutable g : Greet;            
            // Instantiate Greet. Call Constructor
            g = Greet();
            // Call Set Properties
            g.Message = "hello";
            g.Name = "world";
            g.LoopMessage = 5;
            // Call Method 2
            g.Salute();
            // Call Overloaded Method 2.1 and Get Properties
            g.Salute(g.Message, "nemerle", g.LoopMessage);
            // Call Overloaded Method 2.2
            g.Salute("carlos");
            
            // Stop and Exit
            Console.WriteLine("Press any key to exit...");
            _ = Console.Read();
        }
    }
}

Greetings Program - Minimal
// Nemerle Basics
using System;
// Greeting Class
class Greet 
{
    // Fields or Attributes
    mutable message : string;
    mutable name : string;
    mutable loopMessage : int;
    // Properties
    public Message : string 
    {
        get { message; }
        set { message = Capitalize(value); }
    }
    public Name : string {
        get { name; }
        set { name = Capitalize(value); }
    }
    public LoopMessage : int {
        get { loopMessage; }
        set { loopMessage = value; }
    }
    // Constructor
    public this() {
        message = "";
        name = "";
        loopMessage = 0;
    }
    // Overloaded Constructor
    public this(message : string, name : string, loopMessage : int) 
    {
        this.message = message;
        this.name = name;
        this.loopMessage = loopMessage;
    }
    // Method 1
    private Capitalize(val : string): string 
    {
        if (val.Length >= 1) {
            val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1);
        }
        else {
            "";
        }
    }
    // Method 2
    public Salute() : void
    {
        // "for" statement
        for (mutable i = 0; i < loopMessage; i++) {
            Console.WriteLine("{0} {1}!", message, name);
        }
    }
    // Overloaded Method 2.1
    public Salute(message : string, name : string, loopMessage : int) : void 
    {
        // "while" statement
        mutable i = 0;
        while(i < loopMessage) {
            Console.WriteLine("{0} {1}!", Capitalize(message), 
                                Capitalize(name));
            i++;
        }
    }
    // Overloaded Method 2.2
    public Salute(name : string) : void
    {
        // "switch/case" statement is not supported
        // using match statement instead
        def dtNow = DateTime.Now;            
        match (dtNow.Hour) {
            |6|7|8|9|10|11 => message = "good morning,";
            |12|13|14|15|16|17 => message = "good afternoon,";
            |18|19|20|21|22 => message = "good evening,";
            |23|0|1|2|3|4|5 => message = "good night,";
            | _ => message = "huh?"
        }            
        Console.WriteLine("{0} {1}!", Capitalize(message), 
                                Capitalize(name));
    }
}

// Console Program
// Define object and Instantiate Greet. Call Constructor 
def g = Greet();
// Call Set Properties
g.Message = "hello";
g.Name = "world";
g.LoopMessage = 5;
// Call Method 2
g.Salute();
// Call Overloaded Method 2.1 and Get Properties
g.Salute(g.Message, "nemerle", g.LoopMessage);
// Call Overloaded Method 2.2
g.Salute("carlos");

// Stop and Exit
Console.WriteLine("Press any key to exit...");
_ = Console.Read();


And the Output is:


















Nemerle in Indentation Mode

Nemerle provides a very cool feature that allows you write your code in C-Like code blocks { } or Python-like indentation. You can do that using a compiler switch, or by adding a #pragma instruction to your code. Let's look at the Greetings Program (Minimal) and how it looks like after removing all those { and } characters from it, or should I say "Let's see how Pythonic it looks like?" hehe...

#pragma indent

using System;

class Greet

    mutable message : string;
    mutable name : string;
    mutable loopMessage : int;
    
    public Message : string
        get 
            message;
        set 
            message = Capitalize(value);
            
    public Name : string
        get
            name;
        set
            name = Capitalize(value);

    public LoopMessage : int
        get
            loopMessage;
        set
            loopMessage = value;
    
    public this()
        message = "";
        name = "";
        loopMessage = 0
    
    public this(message : string, name : string, loopMessage : int)
        this.message = message;
        this.name = name;
        this.loopMessage = loopMessage;
    
    private Capitalize(val : string): string     
        if (val.Length >= 1) 
            val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1);        
        else 
            "";
    
    public Salute() : void
        for (mutable i = 0; i < loopMessage; i++) 
            Console.WriteLine("{0} {1}!", message, name);
    
    public Salute(message : string, name : string, loopMessage : int) : void     
        mutable i = 0;
        while(i < loopMessage) 
            Console.WriteLine("{0} {1}!", Capitalize(message), Capitalize(name));
            i++;
    
    public Salute(name : string) : void        
        def dtNow = DateTime.Now;            
        match (dtNow.Hour) 
            |6|7|8|9|10|11 => message = "good morning,";
            |12|13|14|15|16|17 => message = "good afternoon,";
            |18|19|20|21|22 => message = "good evening,";
            |23|0|1|2|3|4|5 => message = "good night,";
            | _ => message = "huh?"
                    
        Console.WriteLine("{0} {1}!", Capitalize(message), Capitalize(name));
         
mutable g = Greet()

g.Message = "hello";
g.Name = "world";
g.LoopMessage = 5;

g.Salute()
g.Salute(g.Message, "nemerle", g.LoopMessage);
g.Salute("carlos");

// Stop and Exit
Console.WriteLine("Press any key to exit...");
_ = Console.Read();


Wow, this last example looked too hybrid to me!
(C#-JScript-Boo-Python-F#) = Nemerle!


Auto-Implemented Properties in Nemerle

As with other .NET languages (C#,VB.NET,C++) Nemerle provides built in syntax to create auto-implemented properties. Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The compiler will automatically create a private field to store the property variable in addition to creating the associated get and set procedures.

#pragma indent
using System;

/* In our class, we can void typing the Fields/Attributes 
and go directly to the properties */
class Greet
    //mutable message : string;
    //mutable name : string;
    //mutable loopMessage : int;
    
// using pragma indent
    public Message : string
        get; set;
    public Name : string
        get; set;
    public LoopMessage : int
        get; set;
// or not
    public Message : string {get; set;}
    public Name : string {get; set;}
    public LoopMessage : int {get; set;}

    // then, whenever you want to use them you access them via the Properties.
    // Let's see the example in our constructor
    public this()
        Message = "hola";        
        Name = "mundo";
        LoopMessage = 0;

Wednesday, June 30, 2010

OO Hello World - Nemerle



The Hello World version of the program in Nemerle (a C#-like language with functional features) is here!

Could it be a combination of C# and F#? not in the example below, but based on the features it supports it probably is.


By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples. 

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.

using System;

class Greet 
{
    mutable name : string;
    public this(name : string) 
    {
        this.name = name[0].ToString().ToUpper() + name.Substring(1, name.Length - 1);
    }
    public Salute() : void
    {
        Console.WriteLine("Hello {0}!", name);
    }
}

// Greet the world!
def g = Greet("world");
g.Salute();     

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.

using System;
namespace GreetProgram
{
    internal class Greet 
    {
        private mutable name : string;
        public this(name : string) 
        {
            this.name = name[0].ToString().ToUpper() + name.Substring(1, name.Length - 1);
        }
        public Salute() : void
        {
            Console.WriteLine("Hello {0}!", this.name);
        }
    }

    // Greet the world!
    public module GreetProgram
    {
        public static Main() : void
        {
            def g = Greet("world");
            g.Salute();            
        }
    }
}

The Program Output:













Nemerle Info:
“Nemerle is a high-level statically-typed programming language for the .NET platform. It offers functional, object-oriented and imperative features. It has a simple C#-like syntax and a powerful meta-programming system.
Features that come from the functional land are variants, pattern matching, type inference and parameter polymorphism (aka generics). The meta-programming system allows great compiler extensibility, embedding domain specific languages, partial evaluation and aspect-oriented programming.” Taken from: (http://nemerle.org/What_is_Nemerle)

Appeared:
2003
Current Version:
Developed by:
Kamil Skalski, Michal Moskal, Leszek Pacholski and Pawel Olszta
Creator:
Kamil Skalski, Michal Moskal, Leszek Pacholski and Pawel Olszta
Influenced by:
C# (Anders Hejlsberg) | Lisp (John McCarthy), ML (Robin Milner)
Predecessor Language
Predecessor Appeared
Predecessor Creator
Runtime Target:
CLR
Latest Framework Target:
2.0
Mono Target:
Yes
Allows Unmanaged Code:
Yes
Source Code Extension:
“.n”
Keywords:
60
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
No
Latest IDE Support:
Visual Studio 2008 (shell, pro)
MonoDevelop 2.2
Language Reference:
Extra Info: