Sunday, October 31, 2010

Halloween Programming Languages



Happy Halloween to everybody!

What are the most horrifying Programming Languages you have came across or at least read on the Internet? Those languages that if someone come to you and ask you to Maintain or Extend a program written on them you will probably refuse or at least think twice before accepting?

Here below some of them, which I will certainly say "NO, thanks" straight away.


Malbolge

Malbolge is a public domain esoteric programming language invented by Ben Olmstead in 1998, named after the eighth circle of hell in Dante's Inferno, the Malebolge.

The peculiarity of Malbolge is that it was designed to be the most difficult and esoteric programming language. However, several of the tricks used to make understanding it difficult can be simplified away.

Malbolge was so difficult to understand when it arrived that it took two years for the first Malbolge program to appear. The program was not even written by a human being: it was generated by a beam search algorithm designed by Andrew Cooke and implemented in Lisp.

"Hello world" in Malbolge







(more on Malbolge in:  http://en.wikipedia.org/wiki/Malbolge)

Whitespace

Whitespace is an esoteric programming language developed by Edwin Brady and Chris Morris at the University of Durham (also developers of the Kaya programming language). It was released on 1 April 2003 (April Fool's Day). Its name is a reference to whitespace characters. Unlike most programming languages, which ignore or assign little meaning to most whitespace characters, the Whitespace interpreter ignores any non-whitespace characters. Only spaces, tabs and linefeeds have meaning.[1] An interesting consequence of this property is that a Whitespace program can easily be contained within the whitespace characters of a program written in another language, making the text a polyglot.

The language itself is an imperative stack-based language. The virtual machine on which the programs run has a stack and a heap. The programmer is free to push arbitrary width integers onto the stack (currently there is no implementation of floating point numbers) and can also access the heap as a permanent store for variables and data structures.

"Hello world" in Whitespace
Pink = Space and Purple = Tab




































(more on Whitespace in:  http://en.wikipedia.org/wiki/Whitespace_(programming_language))


Brainfuck

The brainfuck programming language is an esoteric programming language noted for its extreme minimalism. It is a Turing tarpit, designed to challenge and amuse programmers, and is not suitable for practical use.[1] Its name has been variously bowdlerized. The name of the language is generally not capitalized except at the start of a sentence, although it is a proper noun.

Urban Müller created brainfuck in 1993 with the intention of designing a language which could be implemented with the smallest possible compiler,[2] inspired by the 1024-byte compiler for the FALSE programming language.[3] Several brainfuck compilers have been made smaller than 200 bytes. The classic distribution is Müller's version 2, containing a compiler for the Amiga, an interpreter, example programs, and a readme document.

The language consists of eight commands, listed below. A brainfuck program is a sequence of these commands, possibly interspersed with other characters (which are ignored). The commands are executed sequentially, except as noted below; an instruction pointer begins at the first command, and each command it points to is executed, after which it normally moves forward to the next command. The program terminates when the instruction pointer moves past the last command.

"Hello world" in Brainfuck





(more on Brainfuck in:  http://en.wikipedia.org/wiki/Brainfuck)

Definitions and info of each programming language mentioned on this post as well as the hello world examples were taken from Wikipedia.org :)

If you want to know more about each of those languages and others you can find them here:
http://en.wikipedia.org/wiki/Category:Esoteric_programming_languages

What other languages do you think can be listed here?
I was thinking about Assembler, even if for some might be easy, but for those of us that started with structured or object oriented high level languages it looks little bit cryptic.

JRuby - Basics by Example



Continue with the Basics by Example; today's version of the post written in JRuby 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
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

module RbGreetProgram  
    class Greet  
        # Fields or Attributes  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
        # Properties | Getters, Setters  
        def message  
          @message  
        end  
        def message=(val)  
          @message = capitalize(val)  
        end  
        def name  
          @name  
        end  
        def name=(val)  
          @name = capitalize(val)  
        end  
        def loopMessage  
          @loopMessage  
        end  
        def loopMessage=(val)  
          @loopMessage = val  
        end  
        # Constructor or Initializer Method  
        def initialize  
            @message = ""  
            @name = ""  
            @loopMessage = 0  
        end  
        # Overloaded Constructor  
        # No Overloaded Constructors/Initializers Support in Ruby  
        # Method 1  
        def capitalize(val)  
            # "if-then-else" statement  
            if val.length >= 1  
                return val.capitalize  
            else  
                return ""  
            end  
        end  
        private :capitalize  
        # Method 2  
        def salute  
            # "for" statement  
            for i in 0..@loopMessage  
                puts "#@message #@name!"  
            end  
        end  
        # Overloaded Method  
        # No Overloaded Methods Support in Ruby. New methods instead.  
         # Method 2.1  
        def salute21(message, name, loopMessage)  
            # "while" statement  
            i = 0  
            while i < loopMessage do  
                puts "#{capitalize(message)} #{capitalize(name)}!"  
                i += 1  
            end  
        end  
        # Method 2.2  
        def salute22(name)  
            # "switch/case" statement  
            dtNow = GregorianCalendar.new            
            @message = case dtNow.get(Calendar::HOUR_OF_DAY)
                when 6..11 then "good morning,"  
                when 12..17 then "good afternoon,"  
                when 18..22 then "good evening,"  
                when 23,0..5 then "good night,"  
                else "huh?"  
            end  
            puts "#{capitalize(@message)} #{capitalize(name)}!"  
        end  
    end  
  
    # Console Program  
    # Define variable object of type Greet  
    # Instantiate Greet. Call Constructor  
    g = Greet.new  
    # 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, "jRuby", g.loopMessage)  
    # Call Method 2.2  
    g.salute22("carlos")  
    # Stop and exit  
    puts "Press any key to exit..."  
    gets  
end


Greetings Program - Minimal
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

class Greet  
    # Fields or Attributes  
    @message = ""  
    @name = ""  
    @loopMessage = 0  
    # Properties | Getters, Setters  
    def message  
      @message  
    end  
    def message=(val)  
      @message = capitalize(val)  
    end  
    def name  
      @name  
    end  
    def name=(val)  
      @name = capitalize(val)  
    end  
    def loopMessage  
      @loopMessage  
    end  
    def loopMessage=(val)  
      @loopMessage = val  
    end  
    # Constructor or Initializer Method  
    def initialize  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
    end  
    # Overloaded Constructor  
    # No Overloaded Constructors/Initializers Support in Ruby  
    # Method 1  
    def capitalize(val)  
        # "if-then-else" statement  
        if val.length >= 1  
            return val.capitalize  
        else  
            return ""  
        end  
    end  
    private :capitalize  
    # Method 2  
    def salute  
        # "for" statement  
        for i in 0..@loopMessage  
            puts "#@message #@name!"  
        end  
    end  
    # Overloaded Method  
    # No Overloaded Methods Support in Ruby. New methods instead.  
    # Method 2.1  
    def salute21(message, name, loopMessage)  
        # "while" statement  
        i = 0  
        while i < loopMessage do  
            puts "#{capitalize(message)} #{capitalize(name)}!"  
            i += 1  
        end  
    end  
    # Method 2.2  
    def salute22(name)  
        # "switch/case" statement  
        dtNow = GregorianCalendar.new            
        @message = case dtNow.get(Calendar::HOUR_OF_DAY)
            when 6..11 then "good morning,"  
            when 12..17 then "good afternoon,"  
            when 18..22 then "good evening,"  
            when 23,0..5 then "good night,"  
            else "huh?"  
        end  
        puts "#{capitalize(@message)} #{capitalize(name)}!"  
    end  
end  
  
# Console Program  
# Define variable object of type Greet     
# Instantiate Greet. Call Constructor     
g = Greet.new  
# 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, "jRuby", g.loopMessage)     
# Call Method 2.2  
g.salute22("carlos")
# Stop and exit
puts "Press any key to exit..."
gets



And the Output is:





















Where to define Class Fields/Attributes in JRuby

puts "Class Attributes Example:"  
class ClassAttributes  
    # 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 initialize  
        @message = "message" # class field  
        @name = "name"  # class field  
    end  
    # and one more within a public method (loopMessage)  
    def salute  
        @loopMessage = 1 # class field  
        localtest = 0   # local variable    
        puts "#@message, #@name, #@loopMessage"  
    end  
end  
  
# Then, you can access each of them as you normally do:  
f = ClassAttributes.new  
f.salute


Auto-Implemented Properties in JRuby
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.

puts ""  
puts "Auto-Implemented Properties Example:"  
# Ruby basics  
class Greet  
    # Fields or Attributes  
    #@message = ""  
    # Manual Properties | Getters, Setters  
    #def message  
    # @message  
    #end  
    #def message=(val)  
    #  @message = capitalize(val)  
    #end  
      
    # Instead of creating a field and a manual property (as above)  
    # we use the attributes syntax to create our Auto-Implemented Property  
    # that will be linked to our @message class field/attribute  
    attr_accessor :message  
    # you can also create read or write only props using attr_writer|attr_reader  
      
    def initialize  
        @message = ""  
    end  
    def salute  
        puts "#@message"  
    end  
end  
  
g = Greet.new  
# we set the value of message through our write property  
g.message = "hello ruby"  
g.salute  
# or get the value from it as well  
puts g.message


Overloading Constructor and Methods in JRuby

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

puts ""  
puts "Overloaded-like Constructor and Method Example:"  
class Overloading  
    # Constructor with variable arguments  
    def initialize(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            @message = args[0]  
            @name = args[1]  
            @loopMessage = args[2]  
        else  
            @message = 'empty_message'  
            @name = 'empty_name'  
            @loopMessage = 2  
        end  
    end  
    # Method  with variable arguments  
    def salute(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            for i in 1..args[2]  
                puts "#{args[0]}, #{args[1]}!"  
            end  
        else  
            for i in 1..@loopMessage  
                puts "#@message, #@name!"  
            end  
        end  
    end  
end  
  
# and now we use the "overloaded-like" constructor and method  
# calling constructor without parameters  
o1 = Overloading.new  
# calling method without parameters  
o1.salute  
# calling method with parameters  
o1.salute("Hello", "JRuby", 3)  
# calling constructor with with parameters  
o2 = Overloading.new("Hello", "Carlos", 2)  
# calling method without parameters  
o2.salute



And the Output is:




Saturday, October 30, 2010

Jython - Basics by Example



Continue with the Basics by Example; today's version of the post written in Jython 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
# Jython Basics  
import java
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
  
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 = GregorianCalendar()
        hh = dtNow.get(Calendar.HOUR_OF_DAY)
        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, "jython", g.LoopMessage)  
    # Call Method 2.2    
    g.salute22("carlos")    
    # Stop and exit    
    print "Press any key to exit..."    
    sin = Scanner(System.in)  
    line = sin.nextLine()  
    sin.close()  

main()

Greetings Program - Minimal
# Jython Basics  
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
  
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 = GregorianCalendar()
        hh = dtNow.get(Calendar.HOUR_OF_DAY)
        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, "jython", g.LoopMessage)  
# Call Method 2.2    
g.salute22("carlos")  
# Stop and exit    
print "Press any key to exit..."    
sin = Scanner(System.in)  
line = sin.nextLine()  
sin.close()


And the Output is:




















Private Fields and Methods in Jython

"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 Jython

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 Jython

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', 'Jython', 3)  
# calling constructor with with parameters  
o2 = Overloading('Hello', 'Carlos', 2)  
# calling method without parameters  
o2.Salute()


And the Output is:





Fantom - Basics by Example



Continue with the Basics by Example; today's version of the post written in Fantom 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
// Fantom Basics
internal class Greet  
{
    // Fields or Attributes
    private Str? message  
    private Str? name 
    private Int? loopMessage 
    // Properties, Getters and Setters
    public Str Message
    { 
      get { return this.&message }
      set { this.&message = this.capitalize(it) }
    }
    public Str Name
    { 
      get { return this.&name }
      set { this.&name = this.capitalize(it) }
    }
    public Int LoopMessage
    { 
      get { return this.&loopMessage }
      set { this.&loopMessage = it }
    }
    // Constructor
    public new make()
    {   
        this.message = ""
        this.name = ""
        this.loopMessage = 0
    }  
    // Overloaded Constructor
    // No Overloaded Constructor support as designed
    // Method 1
    private Str capitalize(Str val)
    {
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val.capitalize()
        }  
        else  {  
            return ""
        }  
    }
    // Method 2
    public Void salute() 
    {  
        // "for" statement
        for (i:=1; i<=this.loopMessage; i++) 
        {  
            echo("$this.message $this.name!")  
        }  
    }  
    // Overloaded Method
    // No Overloaded Methods Support in Fantom. News methods instead.
    // Method 2.1  
    public Void salute21(Str message, Str name, Int loopMessage) 
    {  
        // "while" statement  
        Int i := 0
        while(i < loopMessage) 
        {  
            echo("${this.capitalize(message)} ${this.capitalize(name)}!")            
            i++
        }  
    }  
    // Method 2.2
    public Void salute22(Str name) 
    {
        // "switch/case" statement  
        DateTime dtNow := DateTime.now();
        switch(dtNow.hour)
        {
            case 6: case 7: case 8: case 9: case 10: case 11:  
                this.message = "good morning," 
            case 12: case 13: case 14: case 15: case 16: case 17:  
                this.message = "good afternoon,"
            case 18: case 19: case 20: case 21: case 22:  
                this.message = "good evening," 
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                this.message = "good night,"
            default:
                this.message = "huh?" 
        }
        echo("${this.capitalize(this.message)} ${this.capitalize(name)}!")            
    }
}  

// Console Program
public class FanGreetProgram  
{  
    public static Void main()  
    {  
        // Define variable object of type Greet and Instantiate. Call Constructor
        Greet g := Greet.make()
        // Call Setters
        g.Message = "hello"
        g.Name = "world"
        g.LoopMessage = 5
        // Call Method 2    
        g.salute()  
        // Overloaded Method 2.1 and Getters    
        g.salute21(g.Message, "fantom", g.LoopMessage)   
        // Overloaded Method 2.2    
        g.salute22("carlos")  

        // Stop and exit    
        echo("Press any key to exit...")
        console := Env.cur
        userInput := console.in.readLine
    }  
}

Greetings Program - Minimal
// Fantom Basics
class Greet  
{
    // Fields or Attributes
    private Str? message  
    private Str? name 
    private Int? loopMessage 
    // Properties, Getters and Setters
    Str Message
    { 
      get { return &message }
      set { &message = capitalize(it) }
    }
    Str Name
    { 
      get { return &name }
      set { &name = capitalize(it) }
    }
    Int LoopMessage
    { 
      get { return &loopMessage }
      set { &loopMessage = it }
    }
    // Constructor
    new make()
    {   
        message = ""
        name = ""
        loopMessage = 0
    }  
    // Overloaded Constructor
    // No Overloaded Constructor support as designed
    // Method 1
    private Str capitalize(Str val)
    {
        // "if-then-else" statement  
        if (val.size >= 1) {  
            return val.capitalize
        }  
        else  {  
            return ""
        }  
    }
    // Method 2
    Void salute() 
    {  
        // "for" statement
        for (i:=1; i<=loopMessage; i++) 
        {  
            echo("$message $name!")  
        }  
    }  
    // Overloaded Method
    // No Overloaded Methods Support in Fantom. News methods instead.
    // Method 2.1  
    Void salute21(Str message, Str name, Int loopMessage) 
    {  
        // "while" statement  
        Int i := 0
        while(i < loopMessage) 
        {              
            echo("${capitalize(message)} ${capitalize(name)}!")
            i++  
        }  
    }  
    // Method 2.2
    Void salute22(Str name) 
    {
        // "switch/case" statement  
        DateTime dtNow := DateTime.now;
        switch(dtNow.hour)
        {
            case 6: case 7: case 8: case 9: case 10: case 11:  
                message = "good morning," 
            case 12: case 13: case 14: case 15: case 16: case 17:  
                message = "good afternoon,"
            case 18: case 19: case 20: case 21: case 22:  
                message = "good evening," 
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                message = "good night,"
            default:
                message = "huh?" 
        }
        echo("${capitalize(message)} ${capitalize(name)}!")
    }
}  

// Console Program
class FanGreetProgram  
{  
    static Void main()  
    {  
        // Define variable object of type Greet and Instantiate. Call Constructor
        Greet g := Greet()
        // Call Setters
        g.Message = "hello"
        g.Name = "world"
        g.LoopMessage = 5
        // Call Method 2    
        g.salute
        // Overloaded Method 2.1 and Getters    
        g.salute21(g.Message, "fantom", g.LoopMessage)   
        // Overloaded Method 2.2    
        g.salute22("carlos")  

        // Stop and exit    
        echo("Press any key to exit...")
        console := Env.cur
        userInput := console.in.readLine
    }  
}


And the Output is:


















Emulating Overloaded Constructor in Fantom
Fantom does not support Overloading Constructors by design, but you can some how "emulate" it by calling the constructor with an initializers list as shown here below.
class Greet  
{
    // defining public fields
    Str? message  
    Str? name 
    Int? loopMessage
    // Constructor
    new make()    
    {   
        echo("greet.make")
        message = "empty_message"
        name = "empty_name"
        loopMessage = 0
    }          
    // Method 2  
    Void Salute()  
    {  
        echo("$this.loopMessage $this.message $this.name!")
    }  
}  

class Program  
{  
    static Void main()  
    {  
        // calling constructor (printing greet.make)
        Greet g := Greet()        
        g.Salute()
        // calling constructor (printing greet.make) and explicitly assigning values to each field
        // this can be done if the fields are defined as public 
        // or you will get a Private field xxx not accessible
        Greet g2 := Greet{ message="hello"; name="world"; loopMessage=5 }
        g2.Salute()
    }  
}

And the Output is:

Friday, October 29, 2010

Groovy - Basics by Example



Continue with the Basics by Example; today's version of the post written in Groovy 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
// Groovy Basics
package GvyGreetProgram

public class Greet {
    // Fields or Attributes
    private String message
    private String name
    private Integer loopMessage    
    // Properties or Getters and Setters
    public String getMessage() {  
        return this.message
    }  
    public void setMessage(String val) {  
        this.message = this.Capitalize(val)
    }  
    public String getName() {  
        return this.name
    }  
    public void setName(String val) {  
        this.name = this.Capitalize(val) 
    }  
    public Integer getLoopMessage() {  
        return this.loopMessage
    }  
    public void setLoopMessage(Integer val) {
        this.loopMessage = val
    }
    // Constructor  
    public def Greet() {  
        this.message = ""
        this.name = ""
        this.loopMessage = 0
    }  
    // Overloaded Constructor  
    public def Greet(String message, String name, Integer loopMessage) {  
        this.message = this.Capitalize(message)
        this.name = this.Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private String Capitalize(String val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    public void Salute() {  
        // "for" statement  
        for (i in 1..this.loopMessage) {  
            println "${this.message} ${this.name}!"  
        }  
    }  
    // Overloaded Method 2.1  
    public void Salute(String message, String name, Integer loopMessage) {  
        // "while" statement  
        Integer i = 0
        while(i < loopMessage) {  
            println "${this.Capitalize(message)} ${this.Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    public void Salute(String name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                this.message = 'good morning,' 
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                this.message = 'good afternoon,'
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                this.message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                this.message = 'good night,'
                break;  
            default:  
                this.message = 'huh?' 
                break;  
        }  
        println "${this.Capitalize(this.message)} ${this.Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
Greet g = new 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(), 'groovy', g.getLoopMessage()) 
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
Scanner sin = new Scanner(System.in)
String line = sin.nextLine()
sin.close()

Greetings Program - Minimal
// Groovy Basics
class Greet {
    // Fields or Attributes
    private def message
    private def name
    private def loopMessage    
    // Properties or Getters and Setters
    def getMessage() {  
        return message
    }  
    def setMessage(val) {  
        message = Capitalize(val)
    }  
    def getName() {  
        return name
    }  
    def setName(val) {  
        name = Capitalize(val) 
    }  
    def getLoopMessage() {  
        return loopMessage
    }  
    def setLoopMessage(val) {
        loopMessage = val
    }
    // Constructor  
    def Greet() {  
        message = ""
        name = ""
        loopMessage = 0
    }  
    // Overloaded Constructor  
    def Greet(message, name, loopMessage) {  
        this.message = Capitalize(message)
        this.name = Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private def Capitalize(val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    def Salute() {  
        // "for" statement
        for (i in 1..loopMessage) {  
            println "$message $name!"  
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message, name, loopMessage) {  
        // "while" statement  
        def i = 0
        while(i < loopMessage) {  
            println "${Capitalize(message)} ${Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                message = 'good morning,'
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                message = 'good afternoon,' 
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                message = 'good night,'
                break;  
            default:  
                message = 'huh?'
        }  
        println "${Capitalize(message)} ${Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
def g = new Greet()
// Call Setters  
g.setMessage('hello')
g.setName('world')
//g.setLoopMessage(5)
g.loopMessage = 5
// Call Method 2  
g.Salute()
// Overloaded Method 2.1 and Getters  
g.Salute(g.getMessage(), 'groovy', g.getLoopMessage())
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
def sin = new Scanner(System.in)
def line = sin.nextLine()
sin.close()


And the Output is:


















Auto-Implemented Properties in Groovy
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.

class Greet {  
    // Fields or Attributes
    // and Autoimplemented Properties (Getters and Setters)
    // To create auto implemented setters and getters you just define the fields with no explicit accessor
    String message = 'empty_message'
    def name = 'empty_name'
    Integer loopMessage = 0
    // if you specify an explicit accessor then you need to define your own explicit Setters and Getters
    // as I did in the minimal and verbose examples (because we needed the capitalize custom code in set properties)
    // Example:
    // public String message = 'empty_message'
    // private def name = 'empty_name'
    // protected Integer loopMessage = 0
    // The only one that will still create an auto-implemented Setter will be "final", but no setter since
    // that's how you do a read-only property.
    def Salute() {
        println "$message $name $loopMessage"
    }
} 
  

g = new Greet()
g.Salute()  
// Calling Auto-implemented Setters
g.setMessage('hello')
g.setName('world')
g.setLoopMessage(5)
g.Salute()  
// we can also access the fields from the class directly
g.message = 'bye'
g.name = 'carlos'
g.loopMessage = 2
// Calling Auto-implemented Getters
println g.getMessage() + ' ' + g.getName() + ' ' + g.getLoopMessage()


And the Output is:



Monday, October 25, 2010

IronRuby - Basics by Example



Continue with the Basics by Example; today's version of the post written in IronRuby 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
# IronRuby basics
require 'mscorlib'

module RbGreetProgram
    class Greet
        # Fields or Attributes
        @message = ""
        @name = ""
        @loopMessage = 0
        # Properties | Getters, Setters
        def message
          @message
        end
        def message=(val)
          @message = capitalize(val)
        end
        def name
          @name
        end
        def name=(val)
          @name = capitalize(val)
        end
        def loopMessage
          @loopMessage
        end
        def loopMessage=(val)
          @loopMessage = val
        end
        # Constructor or Initializer Method
        def initialize
            @message = ""
            @name = ""
            @loopMessage = 0
        end
        # Overloaded Constructor
        # No Overloaded Constructors/Initializers Support in Ruby
        # Method 1
        def capitalize(val)
            # "if-then-else" statement
            if val.length >= 1
                return val.capitalize
            else
                return ""
            end
        end
        private :capitalize
        # Method 2
        def salute
            # "for" statement
            for i in 0..@loopMessage
                puts "#@message #@name!"
            end
        end
        # Overloaded Method
        # No Overloaded Methods Support in Ruby. New methods instead.
         # Method 2.1
        def salute21(message, name, loopMessage)
            # "while" statement
            i = 0
            while i < loopMessage do
                puts "#{capitalize(message)} #{capitalize(name)}!"
                i += 1
            end
        end
        # Method 2.2
        def salute22(name)
            # "switch/case" statement
            dtNow = System::DateTime.Now
            @message = case dtNow.Hour
                when 6..11 then "good morning,"
                when 12..17 then "good afternoon,"
                when 18..22 then "good evening,"
                when 23,0..5 then "good night,"
                else "huh?"
            end
            puts "#{capitalize(@message)} #{capitalize(name)}!"
        end
    end

    # Console Program
    # Define variable object of type Greet
    # Instantiate Greet. Call Constructor
    g = Greet.new
    # 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, "ironRuby", g.loopMessage)
    # Call Method 2.2
    g.salute22("carlos")
    # Stop and exit
    puts "Press any key to exit..."
    gets
end
__END__

Greetings Program - Minimal
# IronRuby basics
class Greet
    # Fields or Attributes
    @message = ""
    @name = ""
    @loopMessage = 0
    # Properties | Getters, Setters
    def message
      @message
    end
    def message=(val)
      @message = capitalize(val)
    end
    def name
      @name
    end
    def name=(val)
      @name = capitalize(val)
    end
    def loopMessage
      @loopMessage
    end
    def loopMessage=(val)
      @loopMessage = val
    end
    # Constructor or Initializer Method
    def initialize
        @message = ""
        @name = ""
        @loopMessage = 0
    end
    # Overloaded Constructor
    # No Overloaded Constructors/Initializers Support in Ruby
    # Method 1
    def capitalize(val)
        # "if-then-else" statement
        if val.length >= 1
            return val.capitalize
        else
            return ""
        end
    end
    private :capitalize
    # Method 2
    def salute
        # "for" statement
        for i in 0..@loopMessage
            puts "#@message #@name!"
        end
    end
    # Overloaded Method
    # No Overloaded Methods Support in Ruby. New methods instead.
    # Method 2.1
    def salute21(message, name, loopMessage)
        # "while" statement
        i = 0
        while i < loopMessage do
            puts "#{capitalize(message)} #{capitalize(name)}!"
            i += 1
        end
    end
    # Method 2.2
    def salute22(name)
        # "switch/case" statement
        dtNow = System::DateTime.Now
        @message = case dtNow.Hour
            when 6..11 then "good morning,"
            when 12..17 then "good afternoon,"
            when 18..22 then "good evening,"
            when 23,0..5 then "good night,"
            else "huh?"
        end
        puts "#{capitalize(@message)} #{capitalize(name)}!"
    end
end

# Console Program
# Define variable object of type Greet   
# Instantiate Greet. Call Constructor   
g = Greet.new
# 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, "ironRuby", g.loopMessage)   
# Call Method 2.2
g.salute22("carlos")
# Stop and exit     
puts "Press any key to exit..."
gets


And the Output is:




















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

puts "Class Attributes Example:"
class ClassAttributes
    # 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 initialize
        @message = "message" # class field
        @name = "name"  # class field
 end
 # and one more within a public method (loopMessage)
 def salute
  @loopMessage = 1 # class field
  localtest = 0   # local variable  
  puts "#@message, #@name, #@loopMessage"
 end
end

# Then, you can access each of them as you normally do:
f = ClassAttributes.new
f.salute

Auto-Implemented Properties in (Iron)Ruby
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.

puts ""
puts "Auto-Implemented Properties Example:"
# Ruby basics
class Greet
    # Fields or Attributes
    #@message = ""
    # Manual Properties | Getters, Setters
    #def message
    # @message
    #end
    #def message=(val)
    #  @message = capitalize(val)
    #end
    
    # Instead of creating a field and a manual property (as above)
    # we use the attributes syntax to create our Auto-Implemented Property
    # that will be linked to our @message class field/attribute
    attr_accessor :message
    # you can also create read or write only props using attr_writer|attr_reader
    
    def initialize
        @message = ""
    end
    def salute
        puts "#@message"
    end
end

g = Greet.new
# we set the value of message through our write property
g.message = "hola ruby"
g.salute
# or get the value from it as well
puts g.message

Overloading Constructor and Methods in (Iron)Ruby

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

puts ""
puts "Overloaded-like Constructor and Method Example:"
class Overloading
    # Constructor with variable arguments
    def initialize(*args)
        # if args list/sequence is not empty we use the arguments,
        # otherwise we use the class fields
        if args.size > 0
            @message = args[0]
            @name = args[1]
            @loopMessage = args[2]
        else
            @message = 'empty_message'
            @name = 'empty_name'
            @loopMessage = 2
        end
    end
    # Method  with variable arguments
    def salute(*args)
        # if args list/sequence is not empty we use the arguments,
        # otherwise we use the class fields
        if args.size > 0
            for i in 1..args[2]
                puts "#{args[0]}, #{args[1]}!"
            end
        else
            for i in 1..@loopMessage
                puts "#@message, #@name!"
            end
        end
    end
end

# and now we use the "overloaded-like" constructor and method
# calling constructor without parameters
o1 = Overloading.new
# calling method without parameters
o1.salute
# calling method with parameters
o1.salute("Hello", "IronRuby", 3)
# calling constructor with with parameters
o2 = Overloading.new("Hello", "Carlos", 2)
# calling method without parameters
o2.salute


And the Output is:


Saturday, October 23, 2010

Phalanger - Basics by Example



Update 1: Porting code examples to Phalanger 3 - syntax changes on namespace use.

Continue with the Basics by Example; today's version of the post written in Phalanger (PHP) 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
<?php  
// Phalanger Basics  
namespace PhpGreetProgram;
use System\DateTime;  

[\Export]  
class Greet  
{  
    // Fields or Attributes  
    private $message;  
    private $name;  
    private $loopMessage;  
    // Getters and Setters. No Properties built-in syntax availabe (yet)  
    public function GetMessage()  
    {  
        return $this->message;  
    }  
    public function SetMessage($value)  
    {  
        $this->message = $this->Capitalize($value);  
    }  
    public function GetName()  
    {  
        return $this->name;  
    }  
    public function SetName($value)  
    {  
        $this->name = $this->Capitalize($value);  
    }  
    public function GetLoopMessage()  
    {  
        return $this->loopMessage;  
    }  
    public function SetLoopMessage($value)  
    {  
        $this->loopMessage = $value;  
    }  
    // Constructor          
    public function __construct()  
    {  
        $this->message = "";  
        $this->name = "";  
        $this->loopMessage = 0;  
    }  
    // Overloaded Constructors   
    // No Overloaded Constructors support in Phalanger          
    // Method 1  
    private function Capitalize($value)  
    {              
        // "if-then-else" statement  
        if (strlen($value) >= 1)  
        {  
            return ucwords($value);  
        }  
        else   
        {  
            return "";  
        }  
    }  
    // Method 2  
    public function Salute()  
    {  
        // "for" statement  
        for ($i = 0; $i < $this->loopMessage; $i++)  
        {  
            echo "{$this->message} {$this->name}!\n";  
        }  
    }  
    // Overloaded Method  
    // No Overloaded Methods Support in Phalanger. News methods instead.  
    // Method 2.1  
    public function Salute21($message, $name, $loopMessage)  
    {  
        // "while" statement  
        $i = 0;  
        while ($i < $loopMessage)  
        {  
            echo "{$this->Capitalize($message)} {$this->Capitalize($name)}!\n";  
            $i++;  
        }  
    }  
    // Method 2.2  
    public function Salute22($name)  
    {  
        // "switch/case" statement  
        $dtNow = DateTime::$Now;              
        switch(intval($dtNow->Hour))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                $this->message = "good morning,";  
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                $this->message = "good afternoon,";  
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                $this->message = "good evening,";  
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                $this->message = "good night,";  
                break;  
            default:  
                $this->message = "huh?";  
                break;  
        }  
        echo "{$this->Capitalize($this->message)} {$this->Capitalize($name)}!\n";  
    }  
}  
  
// Console Program  
class Program  
{  
    public static function Main()  
    {  
        // Define variable of type Greet and instantiate. 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(), "phalanger", $g->GetLoopMessage());  
        // Call Method 2.2  
        $g->Salute22("carlos");  
        // Stop and exit  
        echo "Press any key to exit...";  
        fgets(STDIN);  
        return 0;  
    }  
}  
?>

Greetings Program - Minimal
<?php
// Phalanger Basics  
use System\DateTime;  

class Greet  
{  
    // Fields or Attributes  
    private $message;  
    private $name;  
    private $loopMessage;  
    // Getters and Setters. No Properties built-in syntax availabe (yet)  
    function GetMessage()  
    {  
        return $this->message;  
    }  
    function SetMessage($value)  
    {  
        $this->message = $this->Capitalize($value);  
    }  
    function GetName()  
    {  
        return $this->name;  
    }  
    function SetName($value)  
    {  
        $this->name = $this->Capitalize($value);  
    }  
    function GetLoopMessage()  
    {  
        return $this->loopMessage;  
    }  
    function SetLoopMessage($value)  
    {  
        $this->loopMessage = $value;  
    }  
    // Constructor          
    function __construct()  
    {  
        $this->message = "";  
        $this->name = "";  
        $this->loopMessage = 0;  
    }  
    // Overloaded Constructors   
    // No Overloaded Constructors support in Phalanger          
    // Method 1  
    private function Capitalize($value)  
    {              
        // "if-then-else" statement  
        if (strlen($value) >= 1)  
        {  
            return ucwords($value);  
        }  
        else   
        {  
            return "";  
        }  
    }  
    // Method 2  
    function Salute()  
    {  
        // "for" statement  
        for ($i = 0; $i < $this->loopMessage; $i++)  
        {  
            echo "{$this->message} {$this->name}!\n";  
        }  
    }  
    // Overloaded Method  
    // No Overloaded Methods Support in Phalanger. News methods instead.  
    // Method 2.1  
    function Salute21($message, $name, $loopMessage)  
    {  
        // "while" statement  
        $i = 0;  
        while ($i < $loopMessage)  
        {  
            echo "{$this->Capitalize($message)} {$this->Capitalize($name)}!\n";  
            $i++;  
        }  
    }  
    // Method 2.2  
    function Salute22($name)  
    {  
        // "switch/case" statement  
        $dtNow = DateTime::$Now;              
        switch(intval($dtNow->Hour))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                $this->message = "good morning,";  
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                $this->message = "good afternoon,";  
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                $this->message = "good evening,";  
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                $this->message = "good night,";  
                break;  
            default:  
                $this->message = "huh?";  
        }  
        echo "{$this->Capitalize($this->message)} {$this->Capitalize($name)}!\n";  
    }  
}  
  
// Console Program  
class Program  
{  
    static function Main()  
    {  
        // Define variable of type Greet and instantiate. 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(), "phalanger", $g->GetLoopMessage());  
        // Call Method 2.2  
        $g->Salute22("carlos");  
        // Stop and exit  
        echo "Press any key to exit...";  
        fgets(STDIN);  
    }  
}  
?>

And the Output is:



Emulating Overloaded Constructor in Phalanger (PHP)
PHP and Phalanger do not support Overloading Constructors (at least not so far, in the version I'm using), but there is another way you can "emulate" that by creating one constructor with all parameters you need, but assigning a default value to them and then, validating that if you provide those parameters, you use them, otherwise, default init values will be use as shown here below.

<?
class Greet
{    # Fields or Attributes
    private $message;
    private $name;
    private $loopMessage;    
    # Constructor
    function __construct($message=false, $name=false, $loopMessage=false)
    {
        # Use Constructor parameter only if it is was supplied if not use default
        if($message)
            $this->message = $message;
        else
            $this->message = "bye";
        if($name)
            $this->name = $name;
        else
            $this->name = "carlos";
        if($loopMessage)
            $this->loopMessage = $loopMessage;
        else
            $this->loopMessage = 0;
    }        
    // Method 2
    function Salute()
    {
        echo "{$this->loopMessage} {$this->message} {$this->name}!\n";
    }
}

// Console Program
class Program
{
    static function Main()
    {
        // Call Constructor using Defaults
        $g = new Greet();
        $g->Salute();
        // Call Constructor using Parameters
        $g = new Greet("hello", "world", 5);
        $g->Salute();
        // Stop and exit
        echo "Press any key to exit...";
        fgets(STDIN);
    }
}
?>

And the Output is:

Cobra - Basics by Example



Continue with the Basics by Example; today's version of the post written in Cobra 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
# Cobra Basics
use System
namespace CobraGreetProgram

    class Greet is public
        # Fields or Attributes
        var __message as String
        var __name as String
        var __loopMessage as int
        #Properties
        pro message as String is public
            get
                return __message
            set
                __message = .capitalize(value)
        pro name as String is public
            get
                return __name
            set
                __name = .capitalize(value)
        pro loopMessage as int is public
            get
                return __loopMessage
            set
                __loopMessage = value
        # Constructor
        cue init is public
            base.init
            __message = ''
            __name = ''
            __loopMessage = 0
        # Overloaded Constructor
        cue init(message as String, name as String, loopMessage as int) is public
            base.init        
            __message = message
            __name = name
            __loopMessage = loopMessage
        # Method 1
        def capitalize(val as String) as String is private
            # 'if-then-else' statement
            if val.length >= 1
                return val.capitalized
            else
                return ''
        # Method 2
        def salute is public
            # 'for' statement 
            for i in __loopMessage
                print '[__message] [__name]!'
        # Overloaded Method 2.1
        def salute(message as String, name as String, loopMessage as int) is public
            # 'while' statement 
            i as int = 0
            while i < loopMessage
                print '[.capitalize(message)] [.capitalize(name)]!'
                i+=1
        # Overloaded Method 2.2
        def salute(name as String) is public
            # 'switch/case' statement is not supported  
            # using branch statement instead  
            dtNow as DateTime = DateTime.now
            branch dtNow.hour
                on 6 or 7 or 8 or 9 or 10 or 11, __message = 'good morning,'
                on 12 or 13 or 14 or 15 or 16 or 17, __message = 'good afternoon,'
                on 18 or 19 or 20 or 21 or 22, __message = 'good evening,'
                on 23 or 0 or 1 or 2 or 3 or 4 or 5, __message = 'good night,'
                else, __message = 'huh?'
            print '[.capitalize(__message)] [.capitalize(name)]!'

    # Console Program
    class Program is public
        def main is shared
            # Define object of type Greet and Instantiate. Call Constructor            
            g as Greet = 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, 'cobra', g.loopMessage)
            # Call Overloaded Method 2.2  
            g.salute('carlos')
              
            # Stop and Exit  
            print 'Press any key to exit...'
            Console.read
Greetings Program - Minimal
# Cobra Basics
class Greet
    # Fields or Attributes
    var __message
    var __name
    var __loopMessage
    #Properties
    pro message as String
        get
            return __message
        set
            __message = .capitalize(value)
    pro name as String
        get
            return __name
        set
            __name = .capitalize(value)
    pro loopMessage as int
        get
            return __loopMessage
        set
            __loopMessage = value
    # Constructor
    cue init
        base.init
        __message = ''
        __name = ''
        __loopMessage = 0
    # Overloaded Constructor
    cue init(message as String, name as String, loopMessage as int)
        base.init        
        __message = message
        __name = name
        __loopMessage = loopMessage
    # Method 1
    def capitalize(val as String) as String is private
        # 'if-then-else' statement
        if val.length >= 1
            return val.capitalized
        else
            return ''
    # Method 2
    def salute
        # 'for' statement 
        for i in __loopMessage
            print '[__message] [__name]!'
    # Overloaded Method 2.1
    def salute(message as String, name as String, loopMessage as int)
        # 'while' statement 
        i = 0
        while i < loopMessage
            print '[.capitalize(message)] [.capitalize(name)]!'
            i+=1
    # Overloaded Method 2.2
    def salute(name as String)
        # 'switch/case' statement is not supported  
        # using branch statement instead  
        dtNow = DateTime.now
        branch dtNow.hour
            on 6 or 7 or 8 or 9 or 10 or 11, __message = 'good morning,'
            on 12 or 13 or 14 or 15 or 16 or 17, __message = 'good afternoon,'
            on 18 or 19 or 20 or 21 or 22, __message = 'good evening,'
            on 23 or 0 or 1 or 2 or 3 or 4 or 5, __message = 'good night,'
            else, __message = 'huh?'
        print '[.capitalize(__message)] [.capitalize(name)]!'

# Console Program
class Program
    def main
        # Define object of type Greet and Instantiate. 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, 'cobra', g.loopMessage)
        # Call Overloaded Method 2.2  
        g.salute('carlos')
          
        # Stop and Exit  
        print 'Press any key to exit...'
        Console.read

And the Output is:



Auto-Implemented Properties in Cobra
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.

pro <propname> [ as <type>] [from {var, <backingvariablename>} [= <initvalue>] ]
[<docstring>]


class Greet
    var __message
    var __name
    var __loopMessage
    #Properties
    pro message from __message
    pro name from __name
    pro loopMessage from __loopMessage
    # or you can just say from var as here below. it will look for
    # fields called (_|__)message and (_|__)name and (_|__)loopMessage
    # pro message from var
    # pro name from var
    # pro loopMessage from var
    #Constructor
    cue init
        base.init
        __message = ''
        __name = ''
        __loopMessage = 0    
    def capitalize(val as String) as String is private
        return val.capitalized
    def salute       
        print '[__loopMessage] [__message] [__name]!'

class Program
    def main
        g = Greet()        
        g.message = 'hello'
        g.name = 'world'  
        g.loopMessage = 5        
        g.salute
        Console.read

More about Properties in Cobra's wiki site: http://cobra-language.com/trac/cobra/wiki/Classes

And the Output is:






Unit Test and Contracts in Cobra

As stated in my series post, I'm covering strictly basics OO and other basics constructs on my code examples, but in Cobra's case I would like to add that the way you should be doing Cobra (or... the Cobra-nic style (like in Pythonic je...)) should be using Unit Tests and Contracts right from your code using test and require instructions. However, I will just show an example and keep the explanation for future posts.
Let's see an example

extend String

    def capitalize as String
        test
            assert ''.capitalize == ''
            assert 'x'.capitalize == 'X'
            assert 'X'.capitalize == 'X'
            assert 'cobrA'.capitalize == 'CobrA'
        body
            branch .length
                on 0, return this
                on 1, return .toUpper
                else, return this[0].toString.toUpper + this[1:]

class Greet

    cue init(name as String)
        require name.length > 0
        base.init
        _name = name.capitalize

    get name from var as String
    
    def salute
        print 'Hello [.name]!'


class GreetProgram
    """ Greet the world! """

    def main
        g = Greet('world')
        g.salute

Monday, October 18, 2010

Scala - Basics by Example



Update 1: Porting code examples to Scala 2.10.1 - support for String Interpolation.

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

I was thinking in changing the name of this post to "Scala - OO Basics by Example" because I guess its confusing the fact that Scala is more a Functional Programming language than an Imperative one, even if both paradigms are well supported by the language. At the end I decided to leave it like that, I just want to make clear that you will not find any "Functional Basics" on this post ;) ... As I did with my previous F# post.

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
// Scala Basics  
package com.series  
import scala._    
import java.util.Calendar  
  
// Constructor
// Fields or Attributes
class Greet(private var _message:String = "", 
            private var _name:String = "", 
            private var _loopMessage:Int = 0) {
    //Properties  
    def Message = _message  
    def Message_= (value:String):Unit = _message = Capitalize(value)  
    def Name = _name   
    def Name_= (value:String):Unit = _name = Capitalize(value)  
    def LoopMessage = _loopMessage  
    def LoopMessage_= (value:Int):Unit = _loopMessage = value  
    // Overloaded Constructor  
    def this() = { this("","",0) }   
    // Method 1  
    private def Capitalize(value:String):String = {  
        if (value.length >= 1)  
            value.capitalize  
        else  
            ""  
     }  
    // Method 2  
    def Salute() = {  
        // "for" statement  
        for (i <- 1 to _loopMessage) {              
            println(s"${_message} ${_name}!")
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message:String, name:String, loopMessage:Int) = {  
        // "while" statement  
        var i:Int = 0  
        while (i < loopMessage) {                      
            println(s"${Capitalize(message)} ${Capitalize(name)}!")
            i += 1  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name:String) = {  
        // "switch/case" statement is not supported    
        // using match statement instead  
        val dtNow:Calendar = Calendar.getInstance()  
        val t:Int = dtNow.get(Calendar.HOUR_OF_DAY)      
        t match {  
            case 6|7|8|9|10|11 => _message = "good morning,"    
            case 12|13|14|15|16|17 => _message = "good afternoon,"    
            case 18|19|20|21|22 => _message = "good evening,"    
            case 23|0|1|2|3|4|5 => _message = "good night,"    
            case _ => _message = "huh?"    
            }  
        println(s"${Capitalize(_message)} ${Capitalize(name)}!")  
    }  
}    
   
// Console Program  
object Program {    
    def main(args: Array[String]): Unit = {    
        // Define object of type Greet and Instantiate Greet. Call Constructor   
        val g:Greet = new 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, "scala", g.LoopMessage)  
        // Call Overloaded Method 2.2   
        g.Salute("carlos")  
    }    
}

Greetings Program - Minimal
import java.util.Calendar 
    
// Constructor
// Fields or Attributes
class Greet(private var _message:String = "", 
            private var _name:String = "", 
            private var _loopMessage:Int = 0) {
    //Properties  
    def Message = _message  
    def Message_= (value:String):Unit = _message = Capitalize(value)  
    def Name = _name   
    def Name_= (value:String):Unit = _name = Capitalize(value)  
    def LoopMessage = _loopMessage  
    def LoopMessage_= (value:Int):Unit = _loopMessage = value  
    // Overloaded Constructor  
    def this() = this("","",0)
    // Method 1  
    private def Capitalize(value:String) = {  
        if (value.length >= 1)  
            value.capitalize  
        else  
            ""  
     }  
    // Method 2  
    def Salute() = {  
        // "for" statement  
        for (i <- 1 to _loopMessage) {              
            println(s"${_message} ${_name}!")
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message:String, name:String, loopMessage:Int) = {  
        // "while" statement  
        var i = 0  
        while (i < loopMessage) {                      
            println(s"${Capitalize(message)} ${Capitalize(name)}!")
            i += 1  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name:String) = {  
        // "switch/case" statement is not supported    
        // using match statement instead  
        val dtNow = Calendar.getInstance  
        val t = dtNow.get(Calendar.HOUR_OF_DAY)      
        t match {  
            case 6|7|8|9|10|11 => _message = "good morning,"    
            case 12|13|14|15|16|17 => _message = "good afternoon,"    
            case 18|19|20|21|22 => _message = "good evening,"    
            case 23|0|1|2|3|4|5 => _message = "good night,"    
            case _ => _message = "huh?"    
            }  
        println(s"${Capitalize(_message)} ${Capitalize(name)}!")  
    }  
}    
   
// Console Program  
object Program {    
    def main(args: Array[String]) = {    
        // Define object of type Greet and Instantiate Greet. Call Constructor   
        val g = new 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, "scala", g.LoopMessage)  
        // Call Overloaded Method 2.2   
        g.Salute("carlos")  
    }    
}


And the Output is: