Saturday, September 25, 2010

Nemerle - Basics by Example



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

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

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


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

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

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

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

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


And the Output is:


















Nemerle in Indentation Mode

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

#pragma indent

using System;

class Greet

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

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

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

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

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


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


Auto-Implemented Properties in Nemerle

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

#pragma indent
using System;

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

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

Sunday, September 19, 2010

IronPython - Basics by Example



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

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

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


Greetings Program - Verbose
# IronPython Basics  
import System  
from System import Console, DateTime  
  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0  
    # Properties   
    def getMessage(self):   
        return self.__message  
    def setMessage(self, value):   
        self.__message = self.__capitalize(value)  
    Message = property(getMessage, setMessage)  
    def getName(self):   
        return self.__name  
    def setName(self, value):   
        self.__name = self.__capitalize(value)  
    Name = property(getName, setName)  
    def getLoopMessage(self):   
        return self.__loopMessage  
    def setLoopMessage(self, value):   
        self.__loopMessage = value  
    LoopMessage = property(getLoopMessage, setLoopMessage)  
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0  
    # Overloaded Constructor    
    # No Overloaded Constructors Support in Python  
    # Method 1  
    def __capitalize(self, val):  
        # "if-then-else" statement    
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Method 2    
    def salute(self):    
    # "for" statement  
        for i in range(0, self.__loopMessage):  
            print self.__message, self.__name + '!'  
    # Overloaded Method  
    # No Overloaded Methods Support in Python. New methods instead.  
    # Method 2.1    
    def salute21(self, message, name, loopMessage):  
        # "while" statement  
        i = 0  
        while i < loopMessage:    
            print self.__capitalize(message), self.__capitalize(name) + '!'     
            i = i + 1  
    # Method 2.2  
    def salute22(self, name):    
        # "switch/case" statement is not supported      
        # so I'm using if then else if...   
        dtNow = DateTime.Now  
        hh = dtNow.Hour
        if hh in range(6,12):    
            self.__message = "good morning,"    
        elif hh in range(12,18):    
            self.__message = "good evening,"    
        elif hh in range(18,23):    
            self.__message = "good afternoon,"    
        elif hh == 23 or hh in range(0,6):    
            self.__message = "good night,"    
        else:    
            self.__message = "huh?"    
        print self.__capitalize(self.__message), self.__capitalize(name) + '!'  
  
# Console Program  
def main():  
    # Define variable object of type Greet  
    # Instantiate Greet. Call Constructor  
    g = Greet()    
    # Call Set Properties  
    g.Message = "hello"    
    g.Name = "world"    
    g.LoopMessage = 5   
    # Call Method 2    
    g.salute()  
    # Call Method 2.1 and Get Properties    
    g.salute21(g.Message, "ironPython", g.LoopMessage)  
    # Call Method 2.2    
    g.salute22("carlos")    
    # Stop and exit    
    print "Press any key to exit..."    
    Console.Read()  
  
main()

Greetings Program - Minimal
# IronPython Basics  
from System import Console, DateTime  
  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0  
    # Properties   
    def getMessage(self):   
        return self.__message  
    def setMessage(self, value):   
        self.__message = self.__capitalize(value)  
    Message = property(getMessage, setMessage)  
    def getName(self):   
        return self.__name  
    def setName(self, value):   
        self.__name = self.__capitalize(value)  
    Name = property(getName, setName)  
    def getLoopMessage(self):   
        return self.__loopMessage  
    def setLoopMessage(self, value):   
        self.__loopMessage = value  
    LoopMessage = property(getLoopMessage, setLoopMessage)  
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0  
    # Overloaded Constructor    
    # No Overloaded Constructors Support in Python  
    # Method 1  
    def __capitalize(self, val):  
        # "if-then-else" statement    
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Method 2    
    def salute(self):    
     # "for" statement  
        for i in range(0, self.__loopMessage):  
            print self.__message, self.__name + '!'  
    # Overloaded Method  
    # No Overloaded Methods Support in Python. New methods instead.  
    # Method 2.1    
    def salute21(self, message, name, loopMessage):  
        # "while" statement  
        i = 0  
        while i < loopMessage:    
            print self.__capitalize(message), self.__capitalize(name) + '!'     
            i = i + 1  
    # Method 2.2  
    def salute22(self, name):    
        # "switch/case" statement is not supported      
        # so I'm using if then else if...   
        dtNow = DateTime.Now  
        hh = dtNow.Hour  
        if hh in range(6,12):    
            self.__message = "good morning,"    
        elif hh in range(12,18):    
            self.__message = "good evening,"    
        elif hh in range(18,23):    
            self.__message = "good afternoon,"    
        elif hh == 23 or hh in range(0,6):    
            self.__message = "good night,"   
        else:    
            self.__message = "huh?"    
        print self.__capitalize(self.__message), self.__capitalize(name) + '!'  

# Console Program  
# Define variable object of type Greet  
# Instantiate Greet. Call Constructor  
g = Greet()    
# Call Set Properties  
g.Message = "hello"    
g.Name = "world"    
g.LoopMessage = 5   
# Call Method 2  
g.salute()  
# Call Method 2.1 and Get Properties    
g.salute21(g.Message, "ironPython", g.LoopMessage)  
# Call Method 2.2    
g.salute22("carlos")  
# Stop and exit    
print "Press any key to exit..."    
Console.Read()


And the Output is:


















Private Fields and Methods in (Iron)Python

"There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

Name mangling is intended to give classes an easy way to define 'private' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.)". Taken from: "http://docs.python.org/release/2.5.2/tut/node11.html#SECTION0011600000000000000000"

print 'Private Access Modifier Example:'  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0      
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0   
    # Private Method  
    def __capitalize(self, val):  
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Public Method  
    def Salute(self):         
        for i in range(0, self.__loopMessage):  
            print self.__message, self.__name + '!'      
  
g = Greet()    
# publicly accessing private fields (_classname__fieldname)  
g._Greet__message = "hello"    
g._Greet__name = "world"    
g._Greet__loopMessage = 5   
# Call Public Method  
g.Salute()  
# Call Private Method (_classname__methodname)  
print g._Greet__capitalize('capitalized!')

Where to define Class Fields/Attributes in (Iron)Python

print ''  
print 'Class Attributes Example:'  
class ClassAttributes(object):  
    # You do not need to explicitly add the Fields/Attributes as shown below within the class:  
    # message = ''  
    # name = ''    
    # loopMessage = 0      
    # because they are added to the class as Fields/Attributes the first time they appear in   
    # your code. For example, here below, in the Initialize method,   
    # we have 2 fields (name and message)  
    def __init__(self):    
        self.message = '' # class field  
        self.name = ''  # class field  
    # and one more within a public method (loopMessage)  
    def Salute(self):  
        self.loopMessage = 0 # class field  
        localtest = 0   # local variable  

# Then, you can access each of them as you normally do:  
f = ClassAttributes()  
f.message = 'Hello'  
f.name = 'World'  
f.loopMessage = 5  
  
print f.message, f.name, f.loopMessage

Overloading Constructor and Methods in (Iron)Python

Python does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elif code to handle both(or multiple) cases yourself.

print ''  
print 'Overloaded-like Constructor and Method Example:'  
  
class Overloading(object):  
    # Constructor with variable arguments  
    def __init__(self, *args):  
        # if args list/sequence is not empty we use the arguments,   
        # otherwise we use the class fields  
        if args:     
            self.message = args[0]  
            self.name = args[1]  
            self.loopMessage = args[2]  
        else:  
            self.message = 'empty_message'  
            self.name = 'empty_name'  
            self.loopMessage = 2   
    # Method  with variable arguments  
    def Salute(self, *args):  
        # if args list/sequence is not empty we use the arguments,   
        # otherwise we use the class fields  
        if args:  
            for i in range(0, args[2]):  
                print args[0], args[1] + '!'  
        else:  
            for i in range(0, self.loopMessage):  
                print self.message, self.name + '!'     
  
# and now we use the "overloaded-like" constructor and method  
# calling constructor without parameters  
o1 = Overloading()  
# calling method without parameters  
o1.Salute()  
# calling method with parameters  
o1.Salute('Hello', 'IronPython', 3)  
# calling constructor with with parameters  
o2 = Overloading('Hello', 'Carlos', 2)  
# calling method without parameters  
o2.Salute()


And the Output is:

Monday, September 13, 2010

Boo - Basics by Example



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

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

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


Greetings Program - Verbose
// Boo Basics  
namespace BooGreetProgram  
import System  
  
private class Greet:  
    // Fields or Attributes  
    private message as string  
    private name as string  
    private loopMessage as int  
    // Properties  
    public Message as string:  
        get:      
            return self.message  
        set:  
            self.message = self.Capitalize(value)  
    public Name as string:  
        get:  
            return self.name  
        set:  
            self.name = self.Capitalize(value)  
    public LoopMessage as int:  
        get:  
            return self.loopMessage  
        set:  
            self.loopMessage = value  
    // Constructor  
    public def constructor():  
        self.message = ""  
        self.name = ""  
        self.loopMessage = 0  
    // Overloaded Constructor  
    public def constructor(message as string, name as string, loopMessage as int):  
        self.message = self.Capitalize(message)  
        self.name = self.Capitalize(name)  
        self.loopMessage = loopMessage  
    // Method 1  
    private def Capitalize(val as string) as string:  
        // "if-then-else" statement  
        if val.Length >= 1:  
            return val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1)    
        else:  
            return ""  
    // Method 2  
    public def Salute() as void:  
        // "for" statement  
        for i as int in range(0, self.loopMessage):  
            print "${self.message} ${self.name}!"   
    // Overloaded Method 2.1  
    public def Salute(mesage as string, name as string, loopMessage as int) as void:  
        // "while" statement  
        i as int = 0  
        while i < loopMessage:  
            print "${self.Capitalize(message)} ${self.Capitalize(name)}!"   
            i++  
    // Overloaded Method 2.2  
    public def Salute(name as string) as void:  
        // "switch/case" statement is not supported    
        // so I'm using if then else if...    
        dtNow as DateTime = DateTime.Now    
        hh as int = dtNow.Hour  
        if hh==6 or hh==7 or hh==8 or hh==9 or hh==10 or hh==11:  
            self.message = "good morning,"  
        elif hh == 12 or hh == 13 or hh == 14 or hh == 15 or hh == 16 or hh == 17:  
            self.message = "good evening,"  
        elif hh == 23 or hh == 0 or hh == 1 or hh == 2 or hh == 3 or hh == 4 or hh == 5:  
            self.message = "good night,"  
        else:  
            self.message = "huh?"  
        print "${self.Capitalize(self.message)} ${self.Capitalize(name)}!"   

// Console Program  
public def Main(argv as (string)):    
    // Define variable object of type Greet  
    g as Greet  
    // Instantiate Greet. Call Constructor    
    g = Greet()      
    // Call Set Properties    
    g.Message = "hello"  
    g.Name = "world"  
    g.LoopMessage = 5  
    // Call Method 2  
    g.Salute()  
    // Call Overloaded Method 2.1 and Get Properties  
    g.Salute(g.Message, "boo", g.LoopMessage)  
    // Call Overloaded Method 2.2  
    g.Salute("carlos")  
    // Stop and exit  
    print "Press any key to exit..."  
    Console.ReadKey()

Greetings Program - Minimal
// Boo Basics  
import System  

class Greet:  
    // Fields or Attributes  
    message as string  
    name as string  
    loopMessage as int  
    // Properties  
    Message as string:  
        get:  
            return message  
        set:  
            message = Capitalize(value)  
    Name as string:  
        get:  
            return name  
        set:  
            name = Capitalize(value)  
    LoopMessage as int:  
        get:  
            return loopMessage  
        set:  
            loopMessage = value  
    // Constructor  
    def constructor():  
        message = ""  
        name = ""  
        loopMessage = 0  
    // Overloaded Constructor  
    def constructor(message as string, name as string, loopMessage as int):  
        self.message = Capitalize(message)  
        self.name = Capitalize(name)  
        self.loopMessage = loopMessage  
    // Method 1  
    private def Capitalize(val as string) as string:  
        // "if-then-else" statement  
        if val.Length >= 1:
            return val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1)    
        else:  
            return ""  
    // Method 2  
    def Salute():  
        // "for" statement  
        for i as int in range(0, self.loopMessage):  
            print "${message} ${name}!"   
        // Overloaded Method 2.1  
    def Salute(mesage as string, name as string, loopMessage as int):  
        // "while" statement  
        i = 0  
        while i < loopMessage:  
            print "${Capitalize(message)} ${Capitalize(name)}!"   
            i++  
    // Overloaded Method 2.2  
    def Salute(name as string):  
        // "switch/case" statement is not supported    
        // so I'm using if then else if...    
        dtNow = DateTime.Now    
        hh as int = dtNow.Hour  
        if hh==6 or hh==7 or hh==8 or hh==9 or hh==10 or hh==11:  
            message = "good morning,"  
        elif hh == 12 or hh == 13 or hh == 14 or hh == 15 or hh == 16 or hh == 17:  
            message = "good evening,"  
        elif hh == 23 or hh == 0 or hh == 1 or hh == 2 or hh == 3 or hh == 4 or hh == 5:  
            message = "good night,"  
        else:  
            message = "huh?"  
        print "${Capitalize(message)} ${Capitalize(name)}!"   

// Console Program  
// Define variable object of type Greet and Instantiate Greet. Call Constructor    
g = Greet()      
// Call Set Properties  
g.Message = "hello"  
g.Name = "world"  
g.LoopMessage = 5  
// Call Method 2  
g.Salute()  
// Call Overloaded Method 2.1 and Get Properties  
g.Salute(g.Message, "boo", g.LoopMessage)  
// Call Overloaded Method 2.2  
g.Salute("carlos")  
// Stop and exit  
print "Press any key to exit..."  
Console.ReadKey()


And the Output is:


















Auto-Implemented Properties in Boo

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

//That means that we can omit the Fields/Attributes declaration  
//and go directly to the properties  
class Greet:
 // Fields or Attributes 
 //message as string 
 //name as string
 //loopMessage as int
 // Properties     
 [Property(Message)]
 message as string
 [Property(Name)]
 name as string
 [Property(LoopMessage)]
 loopMessage as int

// then, when ever you want to use them you get and set their value using the  properties or using the auto-generated attributes (different from C# where you need to use the property) 
// Let's see an example in our parameter-less constructor 

 // Constructor
 def constructor():
  self.Message = ""
  self.Name = ""
  self.LoopMessage = 0
        // or
  self.message = ""
  self.name = ""
  self.loopMessage = 0

Sunday, September 12, 2010

JavaFX - Basics by Example



Update 1: This article was done when JavaFX 1.3 version was available and the "JavaFX Script" existed as a separate language for it. From JavaFX version 2.0 this language is now deprecated in favor of Java.


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

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

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


Greetings Program - Verbose
// JavaFX Basics
package FxGreetProgram;

import java.lang.System;
import javafx.*;
import javafx.date.DateTime;
import java.text.SimpleDateFormat;

public class Greet {
    // Fields or Attributes
    //(initialize instead of using parameterless constructor)
    var message: String = "";
    var name: String = "";
    var loopMessage: Integer = 0;
    // Getters and Setters. No Properties built-in syntax available
    public function getMessage():String {
        return this.message;
    };
    public function setMessage(value:String):Void {
        this.message = this.Capitalize(value);
    };
    public function getName():String {
        return this.name;
    };
    public function setName(value:String):Void {
        this.name = this.Capitalize(value);
    };
    public function getLoopMessage():Integer {
        return this.loopMessage;
    };
    public function setLoopMessage(value:Integer):Void {
        this.loopMessage = value;
    };
    // insted of Overloaded Constructor, we use init and/or post-init to initialize
    init {        
        this.message = this.Capitalize(this.message);
        this.name = this.Capitalize(this.name);
        this.loopMessage = this.loopMessage;
    };
    // Method 1
    function Capitalize(val:String):String {
        // "if-then-else" statement
        if (val.length() >= 1) {
            return "{val.substring(0,1).toUpperCase()}{val.substring(1, val.length())}";
        }    
        else  {
            return "";
        }
    };
    // Method 2
    public function Salute():Void {
        // "for" statement
        for (i:Integer in [0..this.loopMessage]) {
            println("{this.message} {this.name}!");
        }
    };
    // Overloaded Method 2.1
    public function Salute(message:String, name:String, loopMessage:Integer):Void {
        // "while" statement
        var i:Integer = 0;
        while(i < loopMessage) {
            println("{this.Capitalize(message)} {this.Capitalize(name)}!");
            i++;
        }
    };
    // Overloaded Method 2.2    
    public function Salute(name:String):Void {
        // "switch/case" statement is not supported
        // so I'm using if then else if...
        //var dtNow:Calendar = Calendar.getInstance();
        var dtNow:DateTime = DateTime{};
        def hh = Long.parseLong(new SimpleDateFormat("HH").format(dtNow.instant));

        if (hh == 6 or hh == 7 or hh == 8 or hh == 9
                or hh == 10 or hh == 11) {
            this.message = "good morning,";
        }
        else if (hh == 12 or hh == 13 or hh == 14 or hh == 15
                or hh == 16 or hh == 17) {
            this.message = "good afternoon,";
        }
        else if (hh == 18 or hh == 19 or hh == 20
                or hh == 21 or hh == 22) {
            this.message = "good evening,";
        }
        else if (hh == 23 or hh == 0 or hh == 1 or hh == 2
                or hh == 3 or hh == 4 or hh == 5) {
            this.message = "good night,";
        }
        else {
            this.message = "huh?";
        }    
        println("{this.Capitalize(this.message)} {this.Capitalize(name)}!");
    };

};

// Console Program
public function run():Integer {
    // Define variable object of type Greet
    var g:Greet;
    // Instantiate Greet. Call Init
    g = Greet {};
    // Call Setters
    g.setMessage("hello");
    g.setName("world");
    g.setLoopMessage(5);
    // Call Method 2
    g.Salute();
    // Overloaded Method 2.1 and Getters
    g.Salute(g.getMessage(), "javaFX", g.getLoopMessage());
    // Overloaded Method 2.2
    g.Salute("carlos");

    // Stop and exit
    println("Press any key to exit...");
    System.in.read();
};

Greetings Program - Minimal
// JavaFX Basics
import java.lang.System;
import javafx.*;
import javafx.date.DateTime;
import java.text.SimpleDateFormat;

class Greet {
    // Fields or Attributes
    //(initialize instead of using parameterless constructor)
    var message = "";
    var name = "";
    var loopMessage = 0;
    // Getters and Setters. No Properties built-in syntax available
    function getMessage() {
        return message;
    }
    function setMessage(value:String) {
        message = Capitalize(value);
    }
    function getName() {
        return name;
    }
    function setName(value:String) {
        name = Capitalize(value);
    }
    function getLoopMessage() {
        return loopMessage;
    }
    function setLoopMessage(value:Integer) {
        loopMessage = value;
    }
    // insted of Overloaded Constructor, we use init and/or post-init to initialize
    init {
        message = Capitalize(message);
        name = Capitalize(name);
        loopMessage = loopMessage;
    }
    // Method 1
    function Capitalize(val:String):String {
        // "if-then-else" statement
        if (val.length() >= 1) {
            return "{val.substring(0,1).toUpperCase()}{val.substring(1, val.length())}";
        }
        else  {
            return "";
        }
    }
    // Method 2
    function Salute() {
        // "for" statement
        for (i:Integer in [0..loopMessage]) {
            println("{message} {name}!");
        }
    }
    // Overloaded Method 2.1
    function Salute(message:String, name:String, loopMessage:Integer) {
        // "while" statement
        var i:Integer = 0;
        while(i < loopMessage) {
            println("{Capitalize(message)} {Capitalize(name)}!");
            i++;
        }
    }
    // Overloaded Method 2.2
    function Salute(name:String) {
        // "switch/case" statement is not supported
        // so I'm using if then else if...
        //var dtNow:Calendar = Calendar.getInstance();
        var dtNow:DateTime = DateTime{};
        def hh = Long.parseLong(new SimpleDateFormat("HH").format(dtNow.instant));

        if (hh == 6 or hh == 7 or hh == 8 or hh == 9
                or hh == 10 or hh == 11) {
            message = "good morning,";
        }
        else if (hh == 12 or hh == 13 or hh == 14 or hh == 15
                or hh == 16 or hh == 17) {
            message = "good afternoon,";
        }
        else if (hh == 18 or hh == 19 or hh == 20
                or hh == 21 or hh == 22) {
            message = "good evening,";
        }
        else if (hh == 23 or hh == 0 or hh == 1 or hh == 2
                or hh == 3 or hh == 4 or hh == 5) {
            message = "good night,";
        }
        else {
            message = "huh?";
        }
        println("{Capitalize(message)} {Capitalize(name)}!");
    }
}

// Console Program
function run() {
    // Define variable object of type Greet and Instantiate Greet. Call Init
    var g = Greet {};
    // Call Setters
    g.setMessage("hello");
    g.setName("world");
    g.setLoopMessage(5);
    // Call Method 2
    g.Salute();
    // Overloaded Method 2.1 and Getters
    g.Salute(g.getMessage(), "javaFX", g.getLoopMessage());
    // Overloaded Method 2.2
    g.Salute("carlos");

    // Stop and exit
    println("Press any key to exit...");
    System.in.read();
}


And the Output is:


















No Private Access Modifier?
JavaFX Access Modifiers: http://download.oracle.com/javafx/1.3/tutorials/core/modifiers/
// Console Program
function run() {
    // Define variable object of type Greet and Instantiate Greet. Call Init
    var g = Greet {};
    // Call Setters
    g.setMessage("hello");
    g.setName("world");
    g.setLoopMessage(5);
    // using attributes and fields because they are non-private
    g.message = "hello";
    g.name = "world";
    g.loopMessage = 5;
    // of course, by doing this you dont get the Capitalize code within the setter...
    // unless you use the Capitalize method because it is also non-private!
    // encapsulation in JavaFX is done via package access modifiers, and, to understand it, 
    // you might want to read about it here below:
    // http://download.oracle.com/javafx/1.3/tutorials/core/modifiers/
    // to know more about JavaFX access modifiers
    g.message = g.Capitalize("hello");
    g.name = g.Capitalize("world");
    g.loopMessage = 5;
    // Call Method 2
    g.Salute();

};