Saturday, February 25, 2012

OO Hello World - Kotlin



The OO Hello World in Kotlin, the "the new language from JetBrains for the JVM", is here!

Project Kotlin is a codename for a statically typed programming language compiled to JVM byte code and JavaScript.

You can see the OO Hello World series 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.
class Greet(name : String) {
  val name : String = name[0].toString().toUpperCase() + name.substring(1, name.length);
  fun salute() {
    println("Hello, ${name}!");
  }
}

// Greet the world!
fun main(args : Array<string>) {
  val g = Greet("carlos");
  g.salute();
}

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

public class Greet(name : String) {
  private val name : String = name[0].toString().toUpperCase() + name.substring(1, name.length);
  public fun salute() {
    println("Hello, ${this.name}!");
  }
}

public fun main(args : Array<string>) {
  val g = Greet("carlos");
  g.salute();
}

The Program Output:





Kotlin Info:

""Project Kotlin" is the codename of a statically-typed JVM-targeted programming language developed by JetBrains intended for industrial use. This is an object-oriented language” Taken from: ( http://confluence.jetbrains.net/display/Kotlin/Welcome )

Appeared:
2011
Current Version:
Developed by:
JetBrains
Creator:
Andrey Breslav
Influenced by:
Groovy (Guillaume Laforge), C# (Anders Hejlsberg)
Java (James Gosling), Scala (Martin Odersky)
Predecessor Language
N/A
Predecessor Appeared
N/A
Predecessor Creator
N/A
Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.kt”
Keywords:
31
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
N/A
Latest IDE Support:
Intellij IDEA
Language Reference:
Extra Info:


OO Hello World - Ceylon



Update 1: Porting code examples to Ceylon M5 - syntax changes on assignent operator, module definition and support for String Interpolation.

The OO Hello World in Ceylon, the "the new language from Red Hat for the JVM", is here!

Ceylon is a general-purpose, imperative, statically-typed, block-structured, object-oriented, higher-order language featuring a syntax similar to Java and C#, and a type system based on the notion of principal types.

You can see the OO Hello World series 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.
class Greet(String name) {   
    String _name = name[0..0].uppercased + name[1...];  
    shared void salute() {  
        print("Hello, ``_name``!");  
    }
} 
  
// Greet the world!  
void run() {  
    value g = Greet("carlos");  
    g.salute();  
}  

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
shared class Greet(String name) {   
    variable String _name = name[0..0].uppercased + name[1...];  
    shared void salute() {  
        print("Hello, ``this._name``!");  
    }  
}  
  
// Greet the world!  
shared void run() {  
    value g = Greet("carlos");  
    g.salute();  
} 

The Program Output:







Ceylon Info:

“Ceylon is a programming language for writing large programs in a team environment. The language is elegant, highly readable, extremely typesafe, and makes it easy to get things done. And it's easy to learn for programmers who are familiar with mainstream languages used in business computing. Ceylon has a full-featured Eclipse-based development environment, allowing developers to take best advantage of the powerful static type system. Programs written in Ceylon execute on any JVM.” Taken from: (http://www.ceylon-lang.org/ )

Appeared:
2011
Current Version:
Developed by:
Red Hat
Creator:
Gavin King
Influenced by:
Java (James Gosling), C# (Anders Hejlsberg)
Predecessor Language
N/A
Predecessor Appeared
N/A
Predecessor Creator
N/A
Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.ceylon”
Keywords:
35
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
N/A
Latest IDE Support:
Eclipse
Language Reference:
Extra Info:


Wednesday, February 22, 2012

Proof of Concept - Zonnon and WPF



Proof of Concept (POC) or a proof of principle is a realization of a certain method or idea(s) to demonstrate its feasibility, or a demonstration in principle, whose purpose is to verify that some concept or theory has the potential of being used. A proof-of-concept is usually small and may or may not be complete. (Wikipedia: Proof of Concept)
Concept is an idea formed from inference.
Inference is the act or process of deriving logical conclusions from premises known or assumed to be true.

Eh voilà! I'm going to proof that you can use WPF and the .NET Framework 4.0 with the latest release of the ETH Zonnon compiler (2010-08-07: Zonnon Compiler 1.2.8) which officially runs on and targets .NET Framework 2.0, and to do that, I will show you some basic .NET hacking that I learned from the Cobra Programming Language guys :)

Let's start with the software you will need (in case you want to try it yourself) to follow this tutorial, then which files you will be using to reference, compile, decompile, edit and recompile, and finally, I will show step by step and with screenshots how to build a basic WPF program using Zonnon.

Software Requirements

Specific Assemblies
  • MSIL Disassembler for .NET 4.0
    • Ildasm.exe - version 4.0.30319.1
  • MSIL Assembler for .NET 4.0
    • Ilasm.exe - version 4.0.30319.1  
    • fusion.dll - version 4.0.30319.1
  • WPF 4.0 Assemblies
    • PresentationCore.dll - version 4.0.30319.1
    • PresentationFramework.dll - version 4.0.30319.1
    • WindowsBase.dll - version 4.0.30319.1
    • System.Xaml.dll - version 4.0.30319.1
  • ETH Zonnon compiler 1.2.8
    • zc.exe - Compiler Launcher Program
    • ETH.Zonnon.dll - Zonnon Compiler

Step #1: Installing ETH Zonnon Compiler 1.2.8

You can download from the link above. I installed in "C:\Zonnon" for ease of use (less typing).
After installation you should have the following files installed:






















Step #2: Project Directory

Create a new folder that will hold our source code and needed assemblies. Again, for ease of use, I created it within the Zonnon installation directoy "C:\Zonnon\wpfznn\" and copy all the assemblies listed in section "Specific Assemblies" except for the Zonnon Compiler assemblies (zc.exe and ETH.Zonnon.dll) which are located in the Zonnon folder.

At the end you should have something like the following:








Step #3: Writing Code

Using your favorite Text Editor, create a new Zonnon source code file for our program "wpfpoc.znn" and save it in our working directory we just created. Now type (or copy/paste) the following Zonnon source code on the file and save again.

module Main;
import 
    System.Byte as Byte,
    System.IO.Path as Path,
    System.Reflection.Assembly as Assembly,
    System.Reflection.AssemblyName as AssemblyName,
    (* WPF imports *)
    System.Xaml,
    System.Windows.Application as Application,
    System.Windows.Window as Window,
    System.Windows.Media.Color as Color,
    System.Windows.Media.SolidColorBrush as SolidColorBrush,    
    System.Windows.Controls.Button as Button,
    System.Windows.Controls.Label as Label,    
    System.Windows.Controls.StackPanel as StackPanel,
    System.Windows.SizeToContent as SizeToContent,
    System.Windows.Thickness as Thickness,
    System.Windows.Media.Brushes as Brushes,
    System.Windows.Media.Effects.DropShadowEffect as DropShadowEffect;
var        
    win: Window;    
    app: Application;
    c: Color;
    scb: SolidColorBrush;
    btn: Button;
    stk: StackPanel;
    asm : Assembly;
    asmn: AssemblyName;
    
procedure {public} onClick(sender: object; args: System.EventArgs);
var lbl: Label;
    msg: string;
begin
    msg := "Welcome to Zonnon!";
    lbl := new Label();
    lbl.FontSize := real(36);
    lbl.Foreground := Brushes.White;
    lbl.Content := msg;    
    stk.Children.Add(lbl);
    win.Height := lbl.Height;
    writeln(msg);
end onClick;
    
begin
    asm := Assembly.GetExecutingAssembly();
    asmn := asm.GetName();

    writeln;    
    writeln("Running Assembly: ", asm.Location:2);
    writeln("Assembly Name: ", asmn.Name:2);
    writeln;    

    win := new Window();
    win.Width := real(400);
    win.Height := real(150);
    win.SizeToContent := SizeToContent.Height;
    win.Title := "Hello Zonnon";        
    
    c.A := Byte(255); c.R := Byte(100); c.G := Byte(150); c.B := Byte(200);
    scb := new SolidColorBrush(c);
    win.Background := scb;
    
    stk := new StackPanel();
    stk.Margin := new Thickness(real(15));
    win.Content := stk;    
    
    btn := new Button();
    btn.Content := "Push Me";
    btn.FontSize := real(24);
    btn.Effect := new DropShadowEffect();
    
    btn.add_Click(onClick);
    stk.Children.Add(btn);
    
    app := new Application();
    app.Run(win);    
    
    (* Stop and exit *)  
    writeln;
    writeln("Press any key to exit...");  
    readln();    
end Main.    

The code is very straightforward and even if it is not commented you can easily understand it... ok ok let's do a quick summary: The program is an executable Zonnon Module program unit. We then import several namespaces and classes from the WPF assemblies and we declare some variables to be used in our main body. The program creates a Window and set its properties. Next, a StackPanel container control is added to the Window's content. We add a Button into the StackPanel we just created and add a Click Event to it. This event calls the onClick procedure that what it does is create a new Label and push it into the Stack (and printing it to the Console) for every click you do to the Button. Finally we create an instance of the Application and call its Run method toshow up our WPF window! Once you close the Window control will be return to the Console Application and wait for any key to be pressed to exit.

For those who read programming books... Alright, yes, this program is a mix of a C# WPF example I found in one of my WPF books and another one from IronPython in Action plus some other stuff of my own :)  CODE REUSE FTW ;)

Ok, let the fun begin!

Step #4: Compilation Completed Successfully - First Problem

We are ready to compile our program for the first time.
Assuming you copied/pasted the code above, let's see what we get by compiling our code into an EXE file.

Open a Windows Cmd window and navigate to our working folder. Then let's use the Zonnon Compiler with the following command line arguments to get our executable assembly.

Assuming you are using the same path structure than me you can copy/pase the following line:

C:\zonnon\zc.exe wpfpoc.znn /entry:Main /ref:PresentationCore.dll /ref:PresentationFramework.dll /ref:System.Xaml.dll /ref:WindowsBase.dll

If you have no syntax error in your code you should see the following result:


















SUCCESS! We did not get any compilation error. Lets run it...

BEEP!
















OK... that makes sense... when the program runs and it arrives to line 53 ( win := new Window(); ) it throws a BadImageFormatException. This is because the PresentationCore.dll and PresentationFramework.dll (where the Window class resides) target a newer .NET Framework than the one our program was compiled against. To fix that, we will change it by manually doing it on the zc.exe file.

Step #5: Let the Hacking Begin - Disassemble the zc.exe Assembly

We are going to make use of the Microsoft IL Dissasembler to change the target .NET Framework of the Zonnon Compiler launcher program from .NET 2.0 to 4.0.

Copy/pase the following command line into your console:

ildasm.exe C:\Zonnon\zc.exe /out=C:\Zonnon\zc.il

The ildasm program will decompile and extract the zc.exe assembly and give us a file containing all its Intermediate Language in a file ".il"

Step #6: Let the Hacking Begin - Change the Target .NET Framework

Open the zc.il file with any Text Editor. and locate the following 2 sections

.assembly extern mscorlib
.assembly extern System

Each of those 2 assemblies have a .ver 2:0:0:0
Change it to: .ver 4:0:0:0 and save.

If you compare the original zc.il and the one after the edit you should get:






















Step #7: Let the Hacking Begin - Assemble the zc.exe Assembly

Now that the target Framework is changed, lets use the Microsoft IL Asembler to regenerate the zc.exe from the edited zc.il file.

Copy/pase the following command line into your console: 

ilasm.exe C:\Zonnon\zc.il /EXE /out=C:\Zonnon\zc.exe

You should get an Operation completed successfully:



























Step #8: Compilation Completed Successfully - Second Problem

Run the compiler command line that we used in Step #4

C:\zonnon\zc.exe wpfpoc.znn /entry:Main /ref:PresentationCore.dll /ref:PresentationFramework.dll /ref:System.Xaml.dll /ref:WindowsBase.dll

You should get the same Compilation completed successfully message.

Run your program again.

BEEP!
















The problem now is that the UI application needs to run in a single Thread.
In C# apps you can solve this using the [STAThread] attribute to the program main method (the entry point) which indicates that the COM threading model for an application is single-threaded apartment (STA). However, it looks like there is no .NET Attributes support on Zonnon (or at least not documented).

I then tried using the Thread object and set the  SetApartmentState property to ApartmentState.STA, but I failed because I was not able to convert an activity to a System.Threading.ThreadStart delegate object so I can succesfully instantiate a Thread.

For more details on the those 2 last paragraphs please have a look at this link: Why is STAThread required?
"When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. "

Step #9: The System.STAThreadAttribute

At the end, I decided to fix it with a dirty hack (IL) again.
To fix this we will be using exaclty the same method we used before, but this time we will change the Main method of our program, but first, let's see how I knew what to change.

I created a C# program that used the [STAThread] attribute.
class Program
{
    // Methods
    [STAThread]
    private static void Main(string[] args)
    {
        //pass
    }
}

I decompiled it using Reflector to see the generated IL code:


















OK, what we see here is that within the Main method, which is the entrypoint method of our assembly, an instance of System.STAThreadAttribute is created. That's all we need to know to fix the problem with our WPF program we need to create that instance ourselves. Don't we?

Step #10: Fixing our WPF Program

Copy/pase the following command line into your console:

ildasm.exe wpfpoc.exe /out=wpfpoc.il

The ildasm program will decompile and extract the wpfpoc.exe assembly and give us a file containing all its Intermediate Language in a file ".il"

Open it in any text editor and go to the main method.


























Wait a second... it already has the System.STAThreadAttribute on it! What's wrong then?

The answer is the .param [0] line just above it. To make it work we need to either move the .custom instance line over the .param [0] or just comment/remove the .param [0] line and save.

I was intrigued by this .param [0] and search about it on the Expert .NET 2.0 IL Assembler Apress book and found the following:

<param_const_def> ::= <b>.param</b> [<sequence>] = <const_type> [ (<value>) ]

is the parameter’s sequence number. This number should not be 0, because
a 0 sequence number corresponds to the return type, and a “default return value” does not
make sense.

So needed or not needed to avoid any risk I opted to move the System.STAThreadAttribute line on top of .param [0]  (maybe an IL expert can explain why this behaviour?)

The code ends up like the following:

























We are ready to re-build our program.

Copy/pase the following command line into your console:

ilasm.exe wpfpoc.il /EXE /out=wpfpoc.exe

You should see a "Operation completed successfully" message.

Step #11: Running the WPF Program

Execute the wpfpoc.exe program from the command line.

Our WPF window will pop up.


















Every time you click on the Push Me button it will push a new Label to the StackPanel and resize the Window. At the same time, it prints the same text to the Console.













Summary

There you go. We finally have a .NET Framework 4.0 WPF program developed using the Zonnon Programming Language. This was just a proof of concept experiment just for fun. I think Zonnon is a very interesting programming language and hope that the people behind it ( ETH Zurich )  keep the good work and bring us a ETH Zonnon Compiler 1.2.9 soon with built in support for WPF and targets the .NET Framework 4.0.

And by the way, this little trick is the same I used in my previous post Factorial and Fibonacci in Zonnon to make use of System.Numerics.dll which is .NET 4.0 compatible only.


Friday, February 10, 2012

Factorial and Fibonacci in Zonnon



Here below a little program in Zonnon 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 Zonnon *)

(* Module (Static Class) *)
module StaticFiborial;
import 
  System.Numerics.BigInteger as BigInteger, 
  System.Diagnostics.Stopwatch as Stopwatch;
(* Static Field *)
var {private} className: string;

  (* Static Method - Factorial Recursive *)
  procedure {public} factorialR(n: integer): BigInteger;
  begin
  if n < 1 then
    return BigInteger.One;
  else
    return BigInteger(n) * BigInteger(factorialR(n - 1));
  end;   
  end factorialR;

  (* Static Method - Factorial Imperative *)
  procedure {public} factorialI(n: integer): BigInteger;
  var i: integer;
    res: BigInteger;
  begin 
    res := BigInteger.One;
    for i := n to 1 by -1 do 
      res := res * BigInteger(i);
    end;    
    return res;
  end factorialI;

  (* Static Method - Fibonacci Recursive *)
  procedure {public} fibonacciR(n: integer): integer{64};
  begin
    if n < 2 then
      return 1;
    else
      return fibonacciR(n - 1) + fibonacciR(n - 2);
    end;
  end fibonacciR;

  (* Static Method - Fibonacci Imperative *)
  procedure {public} fibonacciI(n: integer): integer{64};
  var i, pre, cur, tmp: integer{64};
  begin
    pre := 1;
    cur := 1;
    tmp := 0;
    for i := 2 to n do
      tmp := cur + pre;    
      pre := cur;    
      cur := tmp; 
    end; 
    return cur;
  end fibonacciI;  

  (* Static Method - Benchmarking Algorithms *)
  procedure {public} benchmarkAlgorithm(algorithm: integer; var values: array * of integer);
  var timer: Stopwatch;
    testValue: integer;
    facTimeResult: BigInteger;
    i, fibTimeResult: integer{64};
  begin
    timer := new Stopwatch(); 
    i := 0;   
    testValue := 0;   
    facTimeResult := BigInteger.Zero;
    fibTimeResult := 0;  
    (* "Switch" Flow Control Statement *)  
    case algorithm of    
    1:         
      writeln("Factorial Imperative:");
      (* "For" Loop Statement *)
      for i := 0 to len(values)-1 do
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        facTimeResult := factorialI(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
      end;      
    | 2:
      writeln("Factorial Recursive:");
      (* "While" Loop Statement *)      
      while i < len(values) do
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        facTimeResult := factorialR(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
      end;
    | 3:  
      writeln("Fibonacci Imperative:");
      (* "Repeat" Loop Statement *)
      repeat
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        fibTimeResult := fibonacciI(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
        until i = len(values);
    | 4:  
      writeln("Fibonacci Recursive:");
      (* "Loop" Loop Statement *)
      loop
        testValue := values[i];
        (* Taking Time *)
        timer.Start;
        fibTimeResult := fibonacciR(testValue);
        timer.Stop;
        (* Getting Time *)
        writeln(" (" + string(testValue) + ") = {" + string(timer.Elapsed) + "}");
        i := i + 1;
        if i = len(values) then exit end;
        end;
    else
      (* This code will never be reached. 
      So, I'm "using" fibTimeResult & facTimeResult to avoid compile error:
      Zonnon Compiler, Version 1.2.8.0    
      The variable 'fibTimeResult' is assigned but its value is never used.
      The variable 'facTimeResult' is assigned but its value is never used.*)
      writeln(fibTimeResult);      
      writeln(string(facTimeResult)); (* BigInteger not implicitly converted*)
      writeln("DONG!");  
    end;
  end benchmarkAlgorithm;

  (* funny work around for static init code *)
  procedure {public} init;
  begin  
    (* pass *)
  end init;

(* Contructor | Initializer *)  
begin
  className := "Static Constructor";
  writeln(className);
end StaticFiborial.

(* Instance Class *)
object {ref, public} InstanceFiborial;
import System.Numerics.BigInteger as BigInteger,
  StaticFiborial;
(* Instance Field *)
var {private} className: string;

  (* Instance Method - Factorial Recursive *)
  procedure {public} factorialR(n: integer): BigInteger;
  begin
    (* Calling Static Method *)
    return StaticFiborial.factorialR(n);
  end factorialR;

  (* Instance Method - Factorial Imperative *)
  procedure {public} factorialI(n: integer): BigInteger;
  begin 
    (* Calling Static Method *)
    return StaticFiborial.factorialI(n);
  end factorialI;

  (* Instance Method - Fibonacci Recursive *)
  procedure {public} fibonacciR(n: integer): integer{64};
  begin
    (* Calling Static Method *)
    return StaticFiborial.fibonacciR(n);
  end fibonacciR;

  (* Instance Method - Fibonacci Imperative *)
  procedure {public} fibonacciI(n: integer): integer{64};
  begin
    return StaticFiborial.fibonacciI(n);
  end fibonacciI;
  
(* Instance Contructor | Initializer *)  
begin
  self.className := "Instance Constructor";
  writeln(self.className);
end InstanceFiborial.

(* Console Program *)
module Main;
import StaticFiborial, InstanceFiborial;
const N = 10;
type TestArray = array N of integer;
var i,j: integer;
  ff: InstanceFiborial; 
  values: TestArray;
begin
  writeln;
  writeln("Static Class");  
  (* Calling Static Class and Methods 
  No instantiation needed. Calling method directly from the class *)
  (* calling StaticFiborial.init to execute the static constructor code 
  otherwise the string that is being printed there will appear the first
  time a static method is called. In this case will appear like: 
  FacImp(5) =Static Constructor\n120 *)
  StaticFiborial.init;
  writeln("FacImp(5) =", string(StaticFiborial.factorialI(5)));
  writeln("FacRec(5) =", string(StaticFiborial.factorialR(5)));  
  writeln("FibImp(11)=", string(StaticFiborial.fibonacciI(11)));
  writeln("FibRec(11)=", string(StaticFiborial.fibonacciR(11)));  

  writeln;  
  writeln("Instance Class");
  (* Calling Instance Class and Methods         
  Need to instantiate before using. Calling method from instantiated object *)
  ff := new InstanceFiborial();
  writeln("FacImp(5) =", string(ff.factorialI(5)));
  writeln("FacRec(5) =", string(ff.factorialR(5)));  
  writeln("FibImp(11)=", string(ff.fibonacciI(11)));
  writeln("FibRec(11)=", string(ff.fibonacciR(11)));  
  writeln;

  (* Create a list of integer values to test    
  From 5 to 50 by 5 *)
  j := 0;
  (*for i := 5 to 50 by 5 do *)
  for i := 5 to 50 by 5 do
    values[j] := i;
    j := j + 1;
  end; 

  (* Benchmarking Fibonacci *)
  (* 1 = Factorial Imperative *)
  StaticFiborial.benchmarkAlgorithm(1, values);
  writeln;
  (* 2 = Factorial Recursive *)
  StaticFiborial.benchmarkAlgorithm(2, values);
  writeln;
        
  (* Benchmarking Factorial *)
  (* 3 = Fibonacci Imperative *)
  StaticFiborial.benchmarkAlgorithm(3, values);
  writeln;
  (* 4 = Fibonacci Recursive *)
  StaticFiborial.benchmarkAlgorithm(4, values);
  writeln;

  (* Stop and exit *)
  writeln("Press any key to exit...");
  readln();  
end Main.

And the Output is:





Printing the Factorial and Fibonacci Series
  
module Main;
import
  System.Numerics.BigInteger as BigInteger, 
  System.Text.StringBuilder as StringBuilder;

  (* Using a StringBuilder as a list of string elements *)
  procedure {public} GetFactorialSeries(n: integer): string;
  var i: integer;
    series: StringBuilder;
  begin
    (* Create the String that will hold the list *)
    series := new 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 i := n to 1 by -1 do
      (* and append it to the list *)
      series.Append(i);  
      if i > 1 then
        series.Append(" * ");  
      else   
        series.Append(" = ");   
    end;
    end;  
    (* Get the result from the Factorial Method *)
    (* and append it to the end of the list *)
    series.Append(string(Factorial(n)));
    (* return the list as a string *)
    return string(series);
  end GetFactorialSeries;

  (* Using a StringBuilder as a list of string elements *)
  procedure {public} GetFibonnaciSeries(n: integer): string;
  var i: integer;
    series: StringBuilder;
  begin
    (* Create the String that will hold the list *)  
    series := new 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 i := 2 to n do 
      if i < n then
        series.Append(", ");  
      else  
        series.Append(" = ");  
      end;
      series.Append(string(Fibonacci(i)));  
    end;
    (* return the list as a string *)
    return string(series);
  end GetFibonnaciSeries;
  
  procedure {private} Factorial(n: integer): BigInteger;
  begin
    if n < 1 then
      return BigInteger.One;
    else
      return BigInteger(n) * BigInteger(Factorial(n - 1));
    end;   
  end Factorial;
  
  procedure {private} Fibonacci(n: integer): integer{64};
  begin
    if n < 2 then
      return 1;
    else
      return Fibonacci(n - 1) + Fibonacci(n - 2);
    end;
  end Fibonacci;
    
begin
  writeln;
  (* Printing Factorial Series *)
  writeln();  
  writeln(GetFactorialSeries(5));  
  writeln(GetFactorialSeries(7));  
  writeln(GetFactorialSeries(9));  
  writeln(GetFactorialSeries(11));  
  writeln(GetFactorialSeries(40));  
  (* Printing Fibonacci Series *)
  writeln();  
  writeln(GetFibonnaciSeries(5));  
  writeln(GetFibonnaciSeries(7));  
  writeln(GetFibonnaciSeries(9));  
  writeln(GetFibonnaciSeries(11));  
  writeln(GetFibonnaciSeries(40));  
  
end Main.

And the Output is:





















Mixing Instance and Static Members in the same Class

Normally, instance classes can contain both, instance and static members such as: fields, getters, constructors/initializers, methods, etc. However, Zonnon doesn't support mixing both of them on the Module or Object unit types.

 In the following code I had to create one Module and one Object to workaround this limitation.
 
(* Module (Static Class) 
  You cannot declare a variable of type ModuleName 
  If you try to do that you get a: 
  "'ModuleName' does not denote a type as expected."
*) 
module StaticFiborial;
(* Static Field *)
var {private} staticCount: integer;
  
  (* Static Read-Only Getter 
  You cannot reference your class members with the "self" 
  reference pointer since static members are not instantiated. *)
  procedure {public} StaticCount(): integer;
  begin
    return staticCount;
  end StaticCount;  
  
  (* Static Method *)
  procedure {public} Fibonacci(n: integer);
  begin
    staticCount := staticCount + 1;
    writeln;
    writeln("Fibonacci(" + string(n) + ")");
  end Fibonacci;
  
(* Static Constructor | Initializer *)  
begin
  staticCount := 0; 
  writeln("Static Constructor", staticCount:2);
end StaticFiborial.

(* Object (Instance Class) 
  You cannot try to call a method of ObjectName without an instance.
  If you try to do that you get a:
  "Cannot access to a member of 'ObjectName' 
  because it is object but not an instance of object" *)
object {ref, public} InstanceFiborial;
(* Instance Field *)
var {private} instanceCount: integer;

  (* Instance Read-Only Getter
  Within instance members, you can always use    
  the "self" reference pointer to access your (instance) members. *) 
  procedure {public} InstanceCount(): integer;
  begin
    return self.instanceCount;
  end InstanceCount;

  (* Instance Method *)
  procedure {public} Factorial(n: integer);
  begin
    self.instanceCount := self.instanceCount + 1;
    writeln;
    writeln("Factorial(" + string(n) + ")");
  end Factorial;
  
(* Instance Contructor | Initializer *)  
begin
  self.instanceCount := 0; 
  writeln("Instance Constructor", self.instanceCount:2);
end InstanceFiborial.

module Main;
import StaticFiborial, InstanceFiborial;
var fib, fib2: InstanceFiborial;  
begin  
  writeln;
  (* Calling Static Constructor and Methods 
  No need to instantiate *)  
  StaticFiborial.Fibonacci(5);

  (* Calling Instance Constructor and Methods  
  instance required *)
  fib := new InstanceFiborial();
  fib.Factorial(5);

  StaticFiborial.Fibonacci(15);
  fib.Factorial(5);  

  (* Calling Instance Constructor and Methods  
  for a second object *)
  fib2 := new InstanceFiborial();  
  fib2.Factorial(5);  

  writeln;
  (* Calling Static Getter *)
  writeln("Static Count =", StaticFiborial.StaticCount:2);  
  (* Calling Instance Getter of object 1 and 2 *)
  writeln("Instance 1 Count =", fib.InstanceCount:2);  
  writeln("Instance 2 Count =", fib2.InstanceCount:2);  

end Main.

And the Output is:






















Factorial using System.Int64/integer{64}, System.Double/real{64}, 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 on my previous post in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET execution thrown an Overflow Exception when using the "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.

  
module Main;
import System.Numerics.BigInteger as BigInteger, 
  System.Diagnostics.Stopwatch as Stopwatch;
var 
  timer: Stopwatch;
  facIntResult: integer{64};
  facDblResult: real{64};
  facBigResult: BigInteger;
  i: integer;  
  
  (* Long Factorial *)
  procedure FactorialInt64(n: integer): integer{64}; 
  begin
    if n = 1 then
      return 1{64};
    else  
      return n * FactorialInt64(n - 1);  
    end;
  end FactorialInt64;

  (* Double Factorial *)
  procedure FactorialDouble(n: integer): real{64};
  begin
    if n = 1 then
      return 1.0{64};  
    else  
      return real(n) * FactorialDouble(n - 1);
    end;
  end FactorialDouble;
  
  (* BigInteger Factorial *)
  procedure FactorialBigInteger(n: integer): BigInteger;
  begin
    if n = 1 then
      return BigInteger.One;  
    else  
      return BigInteger(n) * BigInteger(FactorialBigInteger(n - 1));  
    end;
  end FactorialBigInteger;
  
begin
  timer := new Stopwatch();  
  facIntResult := 0{64};
  facDblResult := 0.0{64};  
  facBigResult := BigInteger.Zero;  
  
  writeln;
  writeln("Factorial using Int64");  
  (* Benchmark Factorial using Int64 *)
  (* Overflow Exception!!! *)
  do
    for i:= 5 to 50 by 5 do    
      timer.Start;
      facIntResult := FactorialInt64(i);
      timer.Stop;
      writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
     + string(facIntResult));
    end;  
  on exception do
    (* built-in function reason doesn't work:
 Compile Error: Entity 'reason' is not declared*)
    writeln("Oops!","OverflowException");
  on termination do
    writeln("Oops!","Exception Termination");
  end;

  writeln;
  writeln("Factorial using Double");  
  (* Benchmark Factorial using Double *)
  for i:= 5 to 50 by 5 do    
    timer.Start;
    facDblResult := FactorialDouble(i);
    timer.Stop;
    writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
   + string(facDblResult));
  end;
  
  writeln;
  writeln("Factorial using BigInteger");  
  (* Benchmark Factorial using BigInteger *)
  for i:= 5 to 50 by 5 do    
    timer.Start;
    facBigResult := FactorialBigInteger(i);
    timer.Stop;
    writeln(" (" + string(i) + ") = " + string(timer.Elapsed) + " : " 
   + string(facBigResult));
  end;
end Main.

And the Output is:

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