Showing posts with label Zonnon. Show all posts
Showing posts with label Zonnon. Show all posts

Saturday, February 22, 2014

Arrays and Indexers in Zonnon



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

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

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

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

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

module Str;

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

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

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

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

end Str.

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

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

import Str;

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  (* Array Exceptions *)

  PrintTitle("Common Array Exceptions"); 

  PrintCommonArrayExceptions(nil); 
  PrintCommonArrayExceptions(text);  

  (* Accessing Class Array Elements through Indexer *) 

  PrintTitle("Alphabets"); 

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

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

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

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

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

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

  readln; 
end Main.


The output:






















































































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

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.

Wednesday, August 4, 2010

Zonnon - Basics by Example



The second of a series of basics statements and constructs of .NET/JVM Programming Language is here! This time the language chosen was Zonnon.
If you want to know more details about this interesting Programming Language you can find it here: http://carlosqt.blogspot.com/2010/06/oo-hello-world-zonnon.html

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 do not know the theory part, then 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
(* Zonnon Basics *)
module Main;  
import System;

(* Greeting Class and Contructor(No Args) *)
type {ref, public} Greet = object()
 (* Fields or Attributes *)
 var {private}
  message: string;
  name: string;
  loopMessage: integer;

 (* Getters and Setters - No "Working" Properties Support in version 1.2.7? *)
 procedure {public} GetMessage: string;
 begin  
  return self.message;
 end GetMessage;

 procedure {public} SetMessage(val: string);
 begin
  self.message := val;
 end SetMessage;

 procedure {public} GetName: string;
 begin  
  return self.name;
 end GetName;

 procedure {public} SetName(val: string);
 begin
  self.name := val;
 end SetName;

 procedure {public} GetLoopMessage: integer;
 begin  
  return self.loopMessage;
 end GetLoopMessage;

 procedure {public} SetLoopMessage(val: integer);
 begin
  self.loopMessage := val;
 end SetLoopMessage;

 (* Overloaded Constructor *)
 (* No Overloaded Constructors Support in version 1.2.7 *)

 (* Method 1 *)
 procedure {private} Capitalize(val: string): string;  
 begin
  if val.Length >= 1 then 
   return val.Substring(0, 1).ToUpper() + val.Substring(1, val.Length - 1);
  else
   return "";
  end;
 end Capitalize;  

 (* Method 2 *)
 procedure {public} Salute();  
 var i: integer;
 begin
  (* "for" statement *)
  for i := 0 to self.loopMessage do;
   writeln(self.Capitalize(self.message) + " " + self.Capitalize(self.name) + "!");
  end;   
 end Salute; 

 (* Overloaded Methods *)  
 (* No Overloaded Methods Support in version 1.2.7 *)

 (* Method 2.1 *)
 procedure {public} Salute21(message: string; name: string; loopMessage: integer);
 var i: integer;
 begin
  i := 0;
  (* "while" statement *)
  while i < loopMessage do;
   writeln(self.Capitalize(message) + " " + self.Capitalize(name) + "!");
   i := i + 1;
  end;
 end Salute21;

 (* Method 2.2 *)
 procedure {public} Salute22(name: string);
 var 
  dtNow: System.DateTime;
  time: integer;
 begin
  dtNow := System.DateTime.Now;
  time := dtNow.Hour;
  (* "switch/case" statement *)
  case time of  
      6..11 : 
    self.message := "good morning,"; 
   | 12..17 : 
    self.message := "good afternoon,"; 
   | 18..22 :
    self.message := "good evening,"; 
   (*| 23, 0..5 : this doesnt work in 1.2.8 use the following instead*)
   | 23,0,1,2,3,4,5 :
    self.message := "good night,"; 
   else   
          self.message := "huh?";
  end;   
  writeln(self.Capitalize(self.message) + " " + self.Capitalize(name) + "!");
 end Salute22;

(* Contructor | Initializer *)
begin  
 self.message := "";
 self.name := "";
 self.loopMessage := 0;
end Greet;  

(* Console Program *)
var   
 (* Define object of type Greet *)
 g: Greet;
begin   
 (* Instantiate Greet. Call Constructor *)
  g := new Greet();   
 (* Call Setters *)
 g.SetMessage("hello");
 g.SetName("world");
 g.SetLoopMessage(5);
 (* Call Method 2 *)
 g.Salute();
 (* Call Method 2.1 and Getters *)
 g.Salute21(g.GetMessage(), "zonnon", g.GetLoopMessage());
 (* Call Method 2.2 *)
 g.Salute22("carlos");
            
 (* Stop and exit *)
 writeln("Press any key to exit...");
 readln();
end Main.

Greetings Program - Minimal
(* Zonnon Basics *)
module Main;  
import System;

(* Greeting Class and Contructor(No Args) *)
type {ref} Greet = object
 (* Fields or Attributes *)
 var 
  message, name: string;
  loopMessage: integer;

 (* Getters and Setters - No "Working" Properties Support in version 1.2.7? *)
 procedure {public} GetMessage: string;
 begin  
  return message;
 end GetMessage;

 procedure {public} SetMessage(val: string);
 begin
  message := val;
 end SetMessage;

 procedure {public} GetName: string;
 begin  
  return name;
 end GetName;

 procedure {public} SetName(val: string);
 begin
  name := val;
 end SetName;

 procedure {public} GetLoopMessage: integer;
 begin  
  return loopMessage;
 end GetLoopMessage;

 procedure {public} SetLoopMessage(val: integer);
 begin
  loopMessage := val;
 end SetLoopMessage;

 (* Overloaded Constructor *)
 (* No Overloaded Constructors Support in version 1.2.7 *)

 (* Method 1 *)
 procedure Capitalize(val: string): string;  
 begin
  if val.Length >= 1 then 
   return val.Substring(0, 1).ToUpper() + val.Substring(1, val.Length - 1);
  else
   return "";
  end;
 end Capitalize;  

 (* Method 2 *)
 procedure {public} Salute;  
 var i: integer;
 begin
  (* "for" statement *)
  for i := 0 to loopMessage do;
   writeln(Capitalize(message) + " " + Capitalize(name) + "!");
  end;   
 end Salute; 

 (* Overloaded Methods *)  
 (* No Overloaded Methods Support in version 1.2.7 *)

 (* Method 2.1 *)
 procedure {public} Salute21(message: string; name: string; loopMessage: integer);
 var i: integer;
 begin
  i := 0;
  (* "while" statement *)
  while i < loopMessage do;
   writeln(Capitalize(message) + " " + Capitalize(name) + "!");
   i := i + 1;
  end;
 end Salute21;

 (* Method 2.2 *)
 procedure {public} Salute22(name: string);
 var 
  dtNow: System.DateTime;
  time: integer;
 begin
  dtNow := System.DateTime.Now;
  time := dtNow.Hour;
  (* "switch/case" statement *)
  case time of  
       6..11 : 
    message := "good morning,"; 
   | 12..17 : 
    message := "good afternoon,"; 
   | 18..22 :
    message := "good evening,"; 
    (*| 23, 0..5 : this doesnt work in 1.2.8 use the following instead*)
   | 23,0,1,2,3,4,5 :
    message := "good night,"; 
   else   
          message := "huh?";
  end;   
  writeln(Capitalize(message) + " " + Capitalize(name) + "!");
 end Salute22;

(* Contructor | Initializer *)
begin  
 message := "";
 name := "";
 loopMessage := 0;
end Greet;  

(* Console Program *)
var   
 (* Define object of type Greet *)
 g: Greet;
begin   
 (* Instantiate Greet. Call Constructor *)
  g := new Greet();   
 (* Call Setters *)
 g.SetMessage("hello");
 g.SetName("world");
 g.SetLoopMessage(5);
 (* Call Method 2 *)
 g.Salute();
 (* Call Method 2.1 and Getters *)
 g.Salute21(g.GetMessage(), "zonnon", g.GetLoopMessage());
 (* Call Method 2.2 *)
 g.Salute22("carlos");
            
 (* Stop and exit *)
 writeln("Press any key to exit...");
 readln();
end Main.

And the Output is:


I decided to take out some extra comments I added to the code to explain to myself the missing features of Zonnon (overloaded constructors, overloaded methods and properties), but added them with the code examples in the following code section:

(* Properties: *)
 (* It looks like there is some Properties support, but then you need to define your attributes outside 
  the type, into a definition object and then inherit from it in the type = object definition.
  Then you can start creating get and set procedures that also implement each of the attributes defined
  in the definition object... which in fact looks like a normal procedure with more typing. Now, the 
  thing is that I was not able to make it work... I'm still doing some research on that, but for the 
  time being I decided to use Getters and Setters, BUT, definitively, I will show you here below the syntax 
  for those = Get and Set Properties:*)

  (* Step 1: Create a Definition *)
  definition GreetAttributes;
  var {private}
   message, name: string;    
   loopMessage: integer;
  end GreetAttributes;
  
  (* Step 2: Define your Type and Implement from GreetDataMembers Definition *)
  type {ref, public} Greet = object() implements GreetDataMembers

  (* Step 3: Do not define Attributes on the Type (we will use Definition's Attributes) *)  
  
  (* Step 4: Create a Get Property for message attribute which implements attribute in definition *)
  procedure {get, public} message(): string implements GreetDataMembers.message;
  begin
   return self.message;
  end message;

  (* Step 5: Create a Set Property for message attribute which implements attribute in definition *)
  procedure {set, public} message(val: string) implements GreetDataMembers.message;
  begin
   self.message := val;
  end message;

(* Overloaded Constructors: *)
(* Overloaded Constructors are not supported in version 1.2.7 *)
 (* If you need parameters in the constructor
    You need to define the Greet Type as follows: *)
  
  type {ref, public} Greet = object(message: string; name: string; loopMessage: integer) 

  (*  And then update the Constructor | Initialize section of the Type to initialize the values: *)

  begin  
   self.message := message;
   self.name := name;
   self.loopMessage := 0;
  end Greet;  

(* Overloaded Methods: *)
(* Overloaded Methods are not supported in version 1.2.7 *)
 (* If you try to declare the same method name even if the signature differs it gives the following error message 

  "[2015] Duplicate declaration with the name 'Salute' in the current scope" BEEP!

  So, I'm calling the next methods Salute21 and Salute22 (cuz they suppose to be overloading Method 2
 *)

Sunday, June 27, 2010

OO Hello World - Zonnon



The Hello World version of the program in Zonnon (another Pascal/Oberon inspired language) is here.

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.
module Main;

type {ref} Greet = object 
 var  
  name : string;

 procedure {public} Salute(name: string);
 begin 
  self.name := name.Substring(0, 1).ToUpper() + name.Substring(1, name.Length - 1);  
  writeln("Hello " + name + "!");
 end Salute;
begin
 name := "";
end Greet;

var 
 g: Greet;
begin 
 g := new Greet();
 g.Salute("world");
end Main.


Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
module Main;
import System;

type {public, ref} Greet = object 
 var {private} 
  name : string;

 procedure {public} Salute(name: string);
 begin 
  self.name := name.Substring(0, 1).ToUpper() + name.Substring(1, name.Length - 1);  
  writeln("Hello " + self.name + "!");
 end Salute;
begin
 self.name := "";
end Greet;

var 
 g: Greet;
begin
 g := new Greet();
 g.Salute("world"); 
end Main.


The Program Output:









Zonnon Info:
“Zonnon is a general purpose programming language in the Pascal, Modula-2 and Oberon family. Its conceptual model is based on objects, definitions, implementations and modules. Its computing model is concurrent, based on active objects which interact via syntax controlled dialogs.” Taken from: (http://en.wikipedia.org/wiki/Zonnon)

Appeared:
2003
Current Version:
Developed by:
Jürg Gutknecht
Creator:
Jürg Gutknecht
Influenced by:
Pascal, Oberon, Modula (Niklaus Wirth)
Predecessor Language
Predecessor Appeared
Predecessor Creator
Runtime Target:
CLR
Latest Framework Target:
2.0
Mono Target:
Yes
Allows Unmanaged Code:
No
Source Code Extension:
“.znn”
Keywords:
59
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
No
Standard:
No
Latest IDE Support:
Visual Studio 2008 (shell, pro)
Zonnon Builder
Language Reference:
Extra Info: