Wednesday, July 11, 2012

Factorial and Fibonacci in Ceylon



Update 1: Porting code examples to Ceylon M5 - syntax changes on assignent operator, module definition and support for String Interpolation.
Update 2: Interoperability with java code via .jar containing the Stopwatch class imported as a ceylon module using ceylon import-jar.

Here below a little program in Ceylon that implements 2 modules (+ an extra utility Stopwatch java class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the module called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the execution of the program done by the running function "main".

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

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

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


The Fiborial Program

module com.series.staticfiborial '1.0.0' {
    shared import java.base '7';
    import blog.series.lib '1.0.0';
}

// Factorial and Fibonacci in Ceylon  
  
// Module "Static Class" using top level members  
import java.math { BigInteger { bigone=\iONE, bigzero=\iZERO,  
                                big=\IvalueOf } }  
import blog.series.lib { Stopwatch }  
  
// '(private) Static Field' + Initialization  
variable String _className = "'Static' Constructor";  
  
// Static Initializer Method instead, but need to be explicitly called.  
shared void constructor() {  
    print(_className);  
}  
  
// 'Static' Method - Factorial Recursive    
 shared BigInteger factorialR(Integer n) {    
    if (n == 1) {  
        return bigone;  
    }  
    else {  
        return big(n).multiply(factorialR(n - 1));  
    }    
}    
  
// 'Static' Method - Factorial Imperative    
shared BigInteger factorialI(Integer n) {  
    variable Integer c = n;  
    variable BigInteger res = bigone;  
    while (c > 1) {    
        res = res.multiply(big(c));  
        c--;  
    }  
    return res;  
}    
  
// 'Static' Method - Fibonacci Recursive    
shared Integer fibonacciR(Integer n) {    
    if (n < 2) {   
        return 1;  
    }    
    else {  
        return fibonacciR(n - 1) + fibonacciR(n - 2);  
    }    
}    
  
// 'Static' Method - Fibonacci Imperative    
shared Integer fibonacciI(Integer n) {    
    variable Integer pre = 1;  
    variable Integer cur = 1;  
    variable Integer tmp = 0;  
    for (i in 2..n) {    
        tmp = cur + pre;    
        pre = cur;    
        cur = tmp;    
    }    
    return cur;    
}  
  
// 'Static' Method - Benchmarking Algorithms    
shared void benchmarkAlgorithm(Integer algorithm, Integer[] values) {    
    Stopwatch timer = Stopwatch();  
    variable BigInteger facTimeResult = bigzero;  
    variable Integer fibTimeResult = 0;  
      
    if (algorithm == 1) {  
        print("\nFactorial Imperative:");  
        // "For" Loop Statement    
        for (j in 0..values.size - 1) {  
            if (exists testValue = values[j]) {  
                // Taking Time    
                timer.start();   
                facTimeResult = factorialI(testValue);  
                timer.stop();    
                // Getting Time    
                print(" (``testValue.string``) = ``timer.elapsed``");    
            }              
        }    
    }  
    else if(algorithm == 2) {  
        print("\nFactorial Recursive:");    
        // "While" Loop Statement    
        variable Integer i = 0;  
        while (i < values.size) {  
            if (exists testValue = values[i]) {       
                // Taking Time    
                timer.start();    
                facTimeResult = factorialR(testValue);    
                timer.stop();    
                // Getting Time    
                print(" (``testValue.string``) = ``timer.elapsed``");               
            }  
            i++;  
        }          
    }  
    else if (algorithm == 3) {  
        print("\nFibonacci Imperative:");    
        // "For Each" Loop Statement    
        for (testValue in values) {              
            // Taking Time    
            timer.start();   
            fibTimeResult = fibonacciI(testValue);    
            timer.stop();    
            // Getting Time    
            print(" (``testValue.string``) = ``timer.elapsed``");                        
        }    
    }  
    else if (algorithm == 4) {  
        print("\nFibonacci Recursive:");    
        // "For Each" Loop Statement    
        for (testValue in values) {              
            // Taking Time    
            timer.start();    
            fibTimeResult = fibonacciR(testValue);    
            timer.stop();    
            // Getting Time    
            print(" (``testValue.string``) = ``timer.elapsed``");  
        }          
    }  
    else {  
        print("DONG!");  
    }  
}  

doc "Run the module `com.series.staticfiborial`."  
void run() {  
    // pass    
}  

module com.series.fiborial '1.0.0' {
    import java.base '7';
    shared import com.series.staticfiborial '1.0.0';
}

import java.math { BigInteger }  
import java.util { Scanner }  
import java.lang { System { sin=\Iin } }   
// Import 'Static' Module's 'methods'  
import com.series.staticfiborial { staticFiborial=constructor, benchmarkAlgorithm,  
                                    facI=factorialI, facR=factorialR,  
                                    fibI=fibonacciI, fibR=fibonacciR }  
  
// Instance Class    
class InstanceFiborial(className="Instance Constructor") {    
    // Instance Field and Constructor/Initializer  
    variable String className;  
    print(className);  
    // Instance Method - Factorial Recursive    
    shared BigInteger factorialR(Integer n) {    
        // Calling Static Method    
        return facR(n);    
    }    
    // Instance Method - Factorial Imperative    
    shared BigInteger factorialI(Integer n) {    
        // Calling Static Method    
        return facI(n);    
    }    
    // Instance Method - Fibonacci Recursive    
    shared Integer fibonacciR(Integer n) {    
        // Calling Static Method    
        return fibR(n);    
    }    
    // Instance Method - Fibonacci Imperative    
    shared Integer fibonacciI(Integer n) {    
        // Calling Static Method    
        return fibI(n);    
    }    
}    

doc "Run the module `com.series.fiborial`."  
void main() {  
    print("\n'Static' Class");    
    // Calling 'Static' Class and Methods    
    // No instantiation needed. Calling method directly from the class    
    staticFiborial();    
    print("FacImp(5) = ``facI(5).string``");    
    print("FacRec(5) = ``facR(5).string``");    
    print("FibImp(11)= ``fibI(11).string``");    
    print("FibRec(11)= ``fibR(11).string``");   
    
    print("\nInstance Class");  
    // Calling Instance Class and Methods    
    // Need to instantiate before using. Call method from instantiated object    
    value ff = InstanceFiborial();    
    print("FacImp(5) = ``ff.factorialI(5).string``");  
    print("FacRec(5) = ``ff.factorialR(5).string``");    
    print("FibImp(11)= ``ff.fibonacciI(11).string``");  
    print("FibRec(11)= ``ff.fibonacciR(11).string``");  
    
    // Create a (generic) list of integer values to test    
    // From 5 to 50 by 5        
    Integer[] values = [
        for (i in 5..50)    
            if (i%5==0) i
    ];    

    // Benchmarking Fibonacci    
    // 1 = Factorial Imperative    
    benchmarkAlgorithm(1, values);    
    // 2 = Factorial Recursive    
    benchmarkAlgorithm(2, values);    
    
    // Benchmarking Factorial    
    // 3 = Fibonacci Imperative    
    benchmarkAlgorithm(3, values);    
    // 4 = Fibonacci Recursive    
    benchmarkAlgorithm(4, values);  
    
    // Stop and exit    
    print("Press any key to exit...");   
    value s = Scanner(sin);  
    //String line = s.nextLine();  
    s.nextLine();
    s.close();  
}  

And the Output is:





Printing the Factorial and Fibonacci Series
module com.series.fiborialseries '1.0.0' {
    shared import java.base '7';
}
import java.math { BigInteger { bigone=\iONE,     
                                big=\IvalueOf } }    
      
class Fiborial() {      
    // Using a StringBuilder as a list of string elements        
    shared String getFactorialSeries(Integer n) {        
        // Create the String that will hold the list        
        value series = StringBuilder();        
        // We begin by concatenating the number you want to calculate        
        // in the following format: "!# ="        
        series.append("!");        
        series.append(n.string);    
        series.append(" = ");        
        // We iterate backwards through the elements of the series        
        variable value i = n;        
        while (i > 0) {        
            // and append it to the list        
            series.append(i.string);    
            if (i > 1) {        
                series.append(" * ");    
            }        
            else {        
                series.append(" = ");    
            }    
            i--;        
        }        
        // Get the result from the Factorial Method        
        // and append it to the end of the list        
        series.append(factorial(n).string);        
        // return the list as a string        
        return series.string;     
    }    
        
    // Using a StringBuilder as a list of string elements        
    shared String getFibonnaciSeries(Integer n) {        
        // Create the String that will hold the list        
        value series = StringBuilder();        
        // We begin by concatenating the first 3 values which        
        // are always constant        
        series.append("0, 1, 1");  
        // Then we calculate the Fibonacci of each element        
        // and add append it to the list        
        for (i in 2..n) {        
            if (i < n) {       
                series.append(", ");    
            }    
            else {        
                series.append(" = ");    
            }    
            series.append(fibonacci(i).string);        
        }        
        // return the list as a string        
        return series.string;      
    }        
        
    shared BigInteger factorial(Integer n) {      
        if (n == 1) {        
              return bigone;    
        }    
        else {    
            return big(n).multiply(factorial(n - 1));    
        }             
    }             
        
    shared Integer fibonacci(Integer n) {      
        if (n < 2) {      
            return 1;    
        }    
        else {      
            return fibonacci(n - 1) + fibonacci(n - 2);    
        }    
    }          
}      
    
void run() {    
     // Printing Factorial Series      
    print("");      
    value fiborial = Fiborial();     
    print(fiborial.getFactorialSeries(5));      
    print(fiborial.getFactorialSeries(7));     
    print(fiborial.getFactorialSeries(9));      
    print(fiborial.getFactorialSeries(11));      
    print(fiborial.getFactorialSeries(40));      
    // Printing Fibonacci Series      
    print("");    
    print(fiborial.getFibonnaciSeries(5));      
    print(fiborial.getFibonnaciSeries(7));      
    print(fiborial.getFibonnaciSeries(9));      
    print(fiborial.getFibonnaciSeries(11));     
    print(fiborial.getFibonnaciSeries(40));      
}  

And the Output is:

















Mixing Instance and Static Members in the same Class

In Ceylon it is not possible to define a class with static members. To emulate that you need to create a module with toplevel methods, attributes, and even other instance types/classes.
"There are no static members. Instead, toplevel methods and attributes are declared as direct members of a package. This, along with certain other features, gives the language a more regular block structure." taken from Ceylon documentation.

    
module com.series.staticfiborial '1.0.0' {}
    
// Module "Static Class" using top level members  
  
// 'Static' Field'   
variable Integer _staticCount = 0;    
// 'Static' Read-Only Property/Getter  
shared Integer staticCount {  
    return _staticCount;  
}  
// 'Static' Initializer Method instead, but need to be explicitly called.  
shared void constructor() {  
    print("\nStatic Constructor ``_staticCount.string``");  
}  
// 'Static' Method  
shared void fibonacci(Integer n) {  
    _staticCount++;  
    print("\nFibonacci(``n.string``)");  
}  
  
void run() {  
    // pass  
}  
    
module com.series.fiborial '1.0.0' {
    import com.series.staticfiborial '1.0.0';
}
    
import com.series.staticfiborial { staticCount, fibonacci,  
                                    staticFiborial=constructor }  
  
// Instance Class  
shared class InstanceFiborial(_instanceCount=0) {    
    // Instance Field and Constructor/Initializer  
    variable Integer _instanceCount;      
    print("Instance Constructor ``this._instanceCount.string``");      
    // Instance Read-Only Property/Getter  
    shared Integer instanceCount {  
        return this._instanceCount;  
    }  
    // Instance Method    
    shared void factorial(Integer n) {    
        this._instanceCount++;    
        print("\nFactorial(``n.string``)");    
    }    
}  
  
void main() {  
    // Calling Static Constructor and Methods    
    // No need to instantiate    
    staticFiborial();    
    fibonacci(5);    
    
    // Calling Instance Constructor and Methods    
    // Instance required    
    value fib = InstanceFiborial();    
    fib.factorial(5);    
    
    fibonacci(15);    
    fib.factorial(5);    
    
    // Calling Instance Constructor and Methods    
    // for a second object    
    value fib2 = InstanceFiborial();    
    fib2.factorial(5);    
    
    print("");    
    // Calling Static Property    
    print("Static Count = " + staticCount.string);    
    // Calling Instance Property of object 1 and 2    
    print("Instance 1 Count = " + fib.instanceCount.string);    
    print("Instance 2 Count = " + fib2.instanceCount.string);    
}  

And the Output is:






















Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


module com.series.fiborial '1.0.0' {
    shared import java.base '7';
    import blog.series.lib '1.0.0'; 
}
import java.math { BigInteger { bigone=\iONE, bigzero=\iZERO,  
                                big=\IvalueOf } }  
import blog.series.lib { Stopwatch }  
  
// Long/Integer Factorial      
Integer factorialInt64(Integer n) {    
    if (n == 1) {  
        return 1;  
    }  
    else {  
        return n * factorialInt64(n - 1);  
    }    
}    
  
// Double Factorial    
Float factorialDouble(Integer n) {    
    if (n == 1) {  
        return 1.0;  
    }  
    else {  
        return n * factorialDouble(n - 1);  
    }    
}    
  
// BigInteger Factorial      
BigInteger factorialBigInteger(Integer n) {    
    if (n == 1) {  
        return bigone;  
    }  
    else {  
        return big(n).multiply(factorialBigInteger(n - 1));  
    }    
}     

void main() {  
    value timer = Stopwatch();    
    variable Integer facIntResult = 0;    
    variable Float facDblResult = 0.0;    
    variable BigInteger facBigResult = bigzero;        
      
    print("\nFactorial using Int64");  
    // Benchmark Factorial using Int64    
    for (i in (5..50).by(5)) {  
        timer.start();  
        facIntResult = factorialInt64(i);   
        timer.stop();  
        print(" (``i.string``) = ``timer.elapsed.string`` : ``facIntResult.string``");    
    }  
  
    print("\nFactorial using Double");    
    // Benchmark Factorial using Double  
    for (i in (5..50).by(5)) {  
        timer.start();  
        facDblResult = factorialDouble(i);   
        timer.stop();  
        print(" (``i.string``) = ``timer.elapsed.string`` : ``facDblResult.string``");  
    }  
  
    print("\nFactorial using BigInteger");    
    // Benchmark Factorial using BigInteger  
    for (i in (5..50).by(5)) {  
        timer.start();  
        facBigResult = factorialBigInteger(i);   
        timer.stop();  
        print(" (``i.string``) = ``timer.elapsed.string`` : ``facBigResult.string``");  
    }    
}



And the Output is:

Monday, July 9, 2012

Ceylon - Basics by Example



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

Extending my Basics by Example series to a new language. today's version of the post written in Ceylon.

You can copy and paste the code below in Eclipse 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
module com.series.basics '1.0.0' {
    import java.base '7';
}
// Ceylon Basics  
import java.util { Calendar, GregorianCalendar, Scanner }  
import java.lang { System { sin = \Iin } }  
  
// (Main) Constructor/Initializer  
// Instead of method and constructor overloading,   
// Ceylon supports parameters with default values and sequenced ("varargs") parameters.  
shared class Greet(_name="", _message="", _loopMessage=0) {  
    // Fields or Attributes    
    variable String _name;  
    variable String _message;  
    variable Integer _loopMessage;  
    // Getters and Setters  
    shared String name {  
        return _name;  
    }  
    assign name {  
        _name = this.capitalize(name);  
    }  
    shared String message {  
        return _message;  
    }  
    assign message {  
        _message = this.capitalize(message);  
    }  
    shared Integer loopMessage {  
        return _loopMessage;  
    }  
    assign loopMessage {  
        _loopMessage = loopMessage;  
    }  
    // Overloaded/Secondary Constructor    
    // No overloaded constructors/initializers  
    // Method 1    
    String capitalize(String val) {    
          // "if-then-else" statement    
        if (val.size > 0) {  
            return val[0..0].uppercased + val[1...];  
        }    
        else {  
            return "";  
        }  
     }  
    // Method 2    
    shared void salute() {    
        // "for" statement    
        for(i in 1..this._loopMessage) {    
            print("``this._message`` ``this._name``!");    
        }    
    }    
    // Overloaded Method    
    // No Overloaded Methods Support. New methods instead.    
    // Method 2.1    
    shared void salute21(String message, String name, Integer loopMessage) {    
        // "while" statement    
        variable Integer i = 1;    
        while (i <= loopMessage) {    
            print("``this.capitalize(message)`` ``this.capitalize(name)``!");    
            i++;    
        }    
    }    
    // Overloaded Method    
    // No Overloaded Methods Support. New methods instead.    
    // Method 2.2    
    shared void salute22(String name) {  
        Calendar dtNow = GregorianCalendar();  
        variable Integer hh = dtNow.get(dtNow.\iHOUR_OF_DAY);  
        // Ceylon doc: The type of the switched expression must be an enumerated type.   
        // You can't switch on a String or Integer. (Use if instead.)  
        // if-else-if statement  
        if (hh in 6..11) { this._message = "good morning,"; }   
        else if (hh in 12..17) { this._message = "good afternoon,"; }   
        else if (hh in 18..22) { this._message = "good evening,"; }   
        else if (hh == 23 || hh in 0..5) { this._message = "good night,"; }   
        else { this._message = "huh?"; }  
        print("``this.capitalize(this._message)`` ``this.capitalize(name)``!");  
    }  
  
}  
  
doc "Run the module `com.series.basics`."
shared void run() {  
    // Define variable object of type Greet and Instantiate. Call Constructor      
    value g = Greet();  
    // Call Setter  
    g.message = "hello";    
    g.name = "world";    
    g.loopMessage = 5;    
    // Call Method 2    
    g.salute();  
    // Call Overloaded Method 2.1 and Getter    
    g.salute21(g.message, "Ceylon", g.loopMessage);    
    // Call Overloaded Method 2.2    
    g.salute22("carlos");    
  
    print("Press any key to exit...");  
    Scanner s = Scanner(sin);  
    String line = s.nextLine();  
    s.close();  
}  

Greetings Program - Minimal
module com.series.basics '1.0.0' {
    import java.base '7';
}
// Ceylon Basics  
import java.util { Calendar, GregorianCalendar, Scanner }  
import java.lang { System { sin = \Iin } }  
  
// (Main) Constructor/Initializer  
// Instead of method and constructor overloading,   
// Ceylon supports parameters with default values and sequenced ("varargs") parameters.  
class Greet(_name="", _message="", _loopMessage=0) {  
    // Fields or Attributes    
    variable String _name;  
    variable String _message;  
    variable Integer _loopMessage;  
    // Getters and Setters  
    shared String name {  
        return _name;  
    }  
    assign name {  
        _name = capitalize(name);  
    }  
    shared String message {  
        return _message;  
    }  
    assign message {  
        _message = capitalize(message);  
    }  
    shared Integer loopMessage {  
        return _loopMessage;  
    }  
    assign loopMessage {  
        _loopMessage = loopMessage;  
    }  
    // Overloaded/Secondary Constructor    
    // No overloaded constructors/initializers  
    // Method 1    
    String capitalize(String val) {    
          // "if-then-else" statement    
        if (val.size > 0) {  
            return val[0..0].uppercased + val[1...];  
        }    
        else {  
            return "";  
        }  
     }  
    // Method 2    
    shared void salute() {    
        // "for" statement    
        for(i in 1.._loopMessage) {    
            print("``_message`` ``_name``!");    
        }    
    }    
    // Overloaded Method    
    // No Overloaded Methods Support. New methods instead.    
    // Method 2.1    
    shared void salute21(String message, String name, Integer loopMessage) {    
        // "while" statement    
        variable Integer i = 1;    
        while (i <= loopMessage) {    
            print("``capitalize(message)`` ``capitalize(name)``!");    
            i++;    
        }    
    }    
    // Overloaded Method    
    // No Overloaded Methods Support. New methods instead.    
    // Method 2.2    
    shared void salute22(String name) {  
        Calendar dtNow = GregorianCalendar();  
        variable Integer hh = dtNow.get(dtNow.\iHOUR_OF_DAY);  
        // Ceylon documentation: The type of the switched expression must be an enumerated type.   
        // You can't switch on a String or Integer. (Use if instead.)  
        // if-else-if statement  
        if (hh in 6..11) { _message = "good morning,"; }   
        else if (hh in 12..17) { _message = "good afternoon,"; }   
        else if (hh in 18..22) { _message = "good evening,"; }   
        else if (hh == 23 || hh in 0..5) { _message = "good night,"; }   
        else { _message = "huh?"; }  
        print("``capitalize(_message)`` ``capitalize(name)``!");  
    }  
  
}  
  
void run() {  
    // Define variable object of type Greet and Instantiate. Call Constructor      
    value g = Greet();  
    // Call Setter  
    g.message = "hello";    
    g.name = "world";    
    g.loopMessage = 5;    
    // Call Method 2    
    g.salute();  
    // Call Overloaded Method 2.1 and Getter    
    g.salute21(g.message, "Ceylon", g.loopMessage);    
    // Call Overloaded Method 2.2    
    g.salute22("carlos");    
  
    print("Press any key to exit...");  
    value s = Scanner(sin);  
    s.nextLine();  
    s.close();  
}  


And the Output is:



Note: the following is extracted from Ceylon documentation:
"you don't need to write getters and setters unless you're doing something special with the value you're getting or setting.
Don't ever write code like this in Ceylon:

variable String _name;
shared String name { return _name; }
assign name { _name=name; }

It's not necessary, and there's never any benefit to it."

That is exactly what I'm doing with the setters and loopMessage's getter, but remember that the code is like that just because I'm showing the syntax constructs, more importantly, this helps to compare with other languages. The code above is not intended to teach "good practices" nor "idiomatic" code.

Auto-Implemented Properties in Ceylon

In Ceylon there are no such auto-implemented properties that generate automatically a Java bean like getter/setter, instead you need to use class attributes directly using the shared annotation to make them public.


class UsingAttributesToSetGet() {  
    // Attributes   
    shared variable String name = "";  
    shared variable String message = "";  
    shared variable Integer loopMessage = 0;  
    // Methods    
    shared void salute() {    
        print("``message`` ``name`` ``loopMessage.string``!");   
    }    
}

void run() {  
    value g = UsingAttributesToSetGet();  
    // Set the attribute    
    g.message = "hello";    
    g.name = "world";    
    g.loopMessage = 5;    
    // print them out    
    g.salute();    
    // and print them again using the attribute    
    print("``g.message`` ``g.name`` ``g.loopMessage.string``!");
}  

And the output is:


Sunday, July 8, 2012

Factorial and Fibonacci in Xtend



Here below a little program in Xtend that implements 2 classes (in fact, they are 3 + an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "main".

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

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

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


The Fiborial Program

// Factorial and Fibonacci in Xtend  
package com.series
import com.series.Stopwatch
import java.math.BigInteger
import java.util.List

// Instance Class
// static is not a class modifier in Xtend
class StaticFiborial {
    // Static Field
    private static String className = "'Static' Constructor"
    // Static Constructor/Initializer  
    // no available static constructor support  
    // Static Initializer Method instead, but need to be explicitly invoked  
    def static constructor() {  
        className = "'Static' Constructor"  
        println(className)  
    }  
    // Static Method - Factorial Recursive  
    def static BigInteger factorialR(int n) {
        if (n == 1)  
              return 1BI
        else
            return BigInteger::valueOf(n) * factorialR(n - 1)       
    }
    // Static Method - Factorial Imperative  
    def static BigInteger factorialI(int n) {
        var res = 1BI
        var m = n // method parameters are final
        while (m > 1) {
            res = res * BigInteger::valueOf(m)
            m = m - 1    
        }   
        return res     
    }
    // Static Method - Fibonacci Recursive   
    def static long fibonacciR(int n) {
        if (n < 2)
            return 1L
        else
            return fibonacciR(n - 1) + fibonacciR(n - 2)
    } 
    // Static Method - Fibonacci Imperative
    def static long fibonacciI(int n) {
        var pre = 1L
        var cur = 1L
        var tmp = 0L
        for (int i : 2..n) {
            tmp = cur + pre
            pre = cur
            cur = tmp
        }             
        return cur
    }    
    // Static Method - Benchmarking Algorithms  
      def static void benchmarkAlgorithm(int algorithm, List<Integer> values) {  
        val timer = new Stopwatch  
        var testValue = 0
        var facTimeResult = 0BI  
        var fibTimeResult = 0L 
        var i = 0 
        // "Switch" Flow Control Statement
        switch algorithm {
            case 1: {
                println("\nFactorial Imperative:")  
                // "For" Loop Statement  
                for (int j : 0..values.size - 1) {  
                    testValue = values.get(j).intValue
                    // Taking Time
                    timer.start
                    facTimeResult = factorialI(testValue)  
                    timer.stop 
                    // Getting Time  
                    println(''' («testValue») = «timer.getElapsed»''')
                    }
                }
            case 2: {
                println("\nFactorial Recursive:")    
                // "While" Loop Statement                
                while (i < values.size) {                            
                    testValue = values.get(i).intValue    
                    // Taking Time    
                    timer.start    
                    facTimeResult = factorialR(testValue)    
                    timer.stop    
                    // Getting Time    
                    println(''' («testValue») = «timer.getElapsed»''')
                    i = i + 1    
                }
            }
            case 3: {
                println("\nFibonacci Imperative:")   
                // "Do-While" Loop Statement
                do {    
                    testValue = values.get(i).intValue    
                    // Taking Time    
                    timer.start    
                    fibTimeResult = fibonacciI(testValue)    
                    timer.stop
                    // Getting Time    
                    println(''' («testValue») = «timer.getElapsed»''')
                    i = i + 1        
                } while (i < values.size)    
            }
            case 4: {
                println("\nFibonacci Recursive:")    
                // "For Each" Loop Statement    
                for (int item : values) {    
                    testValue = item;    
                    // Taking Time    
                    timer.start    
                    fibTimeResult = fibonacciR(testValue)    
                    timer.stop    
                    // Getting Time    
                    println(''' («testValue») = «timer.getElapsed»''')
                }    
            }
            default : println("DONG!")
        }
    }
}

package com.series
import com.series.StaticFiborial
import java.math.BigInteger

// Instance Class    
class InstanceFiborial {
    // Instance Field    
    private String className    
    // Instance Constructor    
    new() {    
        this.className = "Instance Constructor"
        println(this.className)
    }    
    // Instance Method - Factorial Recursive    
    def BigInteger factorialR(int n) {    
        // Calling Static Method    
        return StaticFiborial::factorialR(n)    
    }    
    // Instance Method - Factorial Imperative    
    def BigInteger factorialI(int n) {    
        // Calling Static Method
        return StaticFiborial::factorialI(n)
    }    
    // Instance Method - Fibonacci Recursive
    def long fibonacciR(int n) {    
        // Calling Static Method    
        return StaticFiborial::fibonacciR(n)    
    }    
    // Instance Method - Factorial Imperative    
    def long fibonacciI(int n) {    
        // Calling Static Method    
        return StaticFiborial::fibonacciI(n);    
    }    
}

package com.series
import com.series.StaticFiborial
import com.series.InstanceFiborial 
import java.util.List
import java.util.ArrayList
import java.util.Scanner

class FiborialProgram {
    def static main(String[] args) {
        println("\n'Static' Class")    
        // Calling Static Class and Methods    
        // No instantiation needed. Calling method directly from the class
        StaticFiborial::constructor        
        println('''FacImp(5) = «StaticFiborial::factorialI(5)»''')    
        println('''FacRec(5) = «StaticFiborial::factorialR(5)»''')    
        println('''FibImp(11)= «StaticFiborial::fibonacciI(11)»''')    
        println('''FibRec(11)= «StaticFiborial::fibonacciR(11)»''')    

        println("\nInstance Class");    
        // Calling Instance Class and Methods     
        // Need to instantiate before using. Calling method from instantiated object    
        val ff = new InstanceFiborial
        println('''FacImp(5) = «ff.factorialI(5)»''')
        println('''FacRec(5) = «ff.factorialR(5)»''')  
        println('''FibImp(11)= «ff.fibonacciI(11)»''')   
        println('''FibRec(11)= «ff.fibonacciR(11)»''')  
  
        // Create a (generic) list of integer values to test    
        // From 5 to 50 by 5    
        val List<Integer> values = new ArrayList<Integer>
        var i = 5
        while (i < 55) {  
            values.add(i)  
            i = i + 5  
        }
  
        // Benchmarking Fibonacci                         
        // 1 = Factorial Imperative                
        StaticFiborial::benchmarkAlgorithm(1, values)    
        // 2 = Factorial Recursive    
        StaticFiborial::benchmarkAlgorithm(2, values)     
  
        // Benchmarking Factorial                
        // 3 = Fibonacci Imperative    
        StaticFiborial::benchmarkAlgorithm(3, values)    
        // 4 = Fibonacci Recursive    
        StaticFiborial::benchmarkAlgorithm(4, values)     
  
        // Stop and exit    
        println("Press any key to exit...")          
        val in = new Scanner(System::in)    
        val line = in.nextLine    
        in.close         
    }
}

And the Output is:





Printing the Factorial and Fibonacci Series
package com.series
import java.math.BigInteger
import java.lang.StringBuffer

class Fiborial {
    // Using a StringBuffer as a list of string elements  
    def static String getFactorialSeries(int n) {  
        // Create the String that will hold the list  
        val series = new StringBuffer  
        // We begin by concatenating the number you want to calculate  
        // in the following format: "!# ="  
        series.append("!")  
        series.append(n) 
        series.append(" = ")  
        // We iterate backwards through the elements of the series  
        var i = n  
        while (i > 0) {  
            // and append it to the list  
            series.append(i)  
            if (i > 1)  
                series.append(" * ")  
            else  
                series.append(" = ")  
            i = i - 1  
        }  
        // Get the result from the Factorial Method  
        // and append it to the end of the list  
        series.append(factorial(n))  
        // return the list as a string  
        return series.toString
    }  
  
    // Using a StringBuffer as a list of string elements  
    def static String getFibonnaciSeries(int n)  
    {  
        // Create the String that will hold the list  
        val series = new StringBuffer  
        // We begin by concatenating the first 3 values which  
        // are always constant  
        series.append("0, 1, 1")
        // Then we calculate the Fibonacci of each element  
        // and add append it to the list  
        for (int i : 2..n) {  
            if (i < n)  
                series.append(", ")  
            else  
                series.append(" = ")  
            series.append(fibonacci(i))  
        }  
        // return the list as a string  
        return series.toString
    }  
  
    def static BigInteger factorial(int n) {
        if (n == 1)  
              return 1BI
        else
            return BigInteger::valueOf(n) * factorial(n - 1)       
    }       
  
    def static long fibonacci(int n) {
        if (n < 2)
            return 1L
        else
            return fibonacci(n - 1) + fibonacci(n - 2)
    }    
}

package com.series
import com.series.Fiborial

class FiborialProgram {
    def static void main(String[] args) {
        // Printing Factorial Series  
        println 
        println(Fiborial::getFactorialSeries(5))
        println(Fiborial::getFactorialSeries(7))  
        println(Fiborial::getFactorialSeries(9))  
        println(Fiborial::getFactorialSeries(11))  
        println(Fiborial::getFactorialSeries(40))  
        // Printing Fibonacci Series  
        println 
        println(Fiborial::getFibonnaciSeries(5))  
        println(Fiborial::getFibonnaciSeries(7))  
        println(Fiborial::getFibonnaciSeries(9))  
        println(Fiborial::getFibonnaciSeries(11))  
        println(Fiborial::getFibonnaciSeries(40))  
    }
}

And the Output is:

















Mixing Instance and Static Members in the same Class

Instance classes can contain both, instance and static members such as: fields, getters/setters, constructors/initializers, methods, etc.

package com.series

class Fiborial {
    // Instance Field    
    var int instanceCount
    // Static Field    
    static var int staticCount
    // Instance Read-Only Getter    
    // Within instance members, you can always use      
    // the "this" reference pointer to access your (instance) members.    
    def int getInstanceCount() {    
        return this.instanceCount     
    }    
    // Static Read-Only Getter        
    // As with Static Methods, you cannot reference your class members    
    // with the "this" reference pointer since static members are not    
    // instantiated.            
    def static int getStaticCount() {    
        return staticCount
    }    
    // Instance Constructor    
    public new() {    
        this.instanceCount = 0
        println    
        println('''Instance Constructor «this.instanceCount»''')   
    }    
    // Static Constructor 
    // not supported in Xtend. Constructor cannot be static.
    // using an explicit initializer method instead    
    def static constructor() { 
        staticCount = 0
        println 
        println('''Static Constructor «staticCount»''') 
    }    
    // Instance Method    
    def void factorial(int n) {    
        this.instanceCount =  this.instanceCount + 1
        println    
        println('''Factorial(«n»)''')    
    }    
  
    // Static Method    
    def static void fibonacci(int n) {    
        staticCount = staticCount + 1
        println    
        println('''Fibonacci(«n»)''');    
    }                    
}

package com.series
import com.series.Fiborial

class FiborialProgram {
    def static void main(String[] args) {
        // Calling Static Initializer and Methods  
        // No need to instantiate  
        Fiborial::constructor  
        Fiborial::fibonacci(5)  
      
        // Calling Instance Constructor and Methods  
        // Instance required  
        val fib = new Fiborial  
        fib.factorial(5)  
      
        Fiborial::fibonacci(15)  
        fib.factorial(5)  
      
        // Calling Instance Constructor and Methods  
        // for a second object  
        val fib2 = new Fiborial  
        fib2.factorial(5)  
      
        println
        // Calling Static Property  
        println('''Static Count = «Fiborial::getStaticCount»''')  
        // Calling Instance Property of object 1 and 2  
        println('''Instance 1 Count = «fib.getInstanceCount»''')  
        println('''Instance 2 Count = «fib2.getInstanceCount»''')          
    } 
}

And the Output is:























Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series
import com.series.Stopwatch
import java.math.BigInteger

class Fiborial {
    def static void main(String[] args) {
        val timer = new Stopwatch  
        var facIntResult = 0L
        var facDblResult  = 0d  
        var facBigResult = 0BI 
        var i = 5
        
        println("\nFactorial using Int64")  
        // Benchmark Factorial using Int64  
        while (i < 55) {  
            timer.start
            facIntResult = factorialInt64(i)  
            timer.stop  
              println(''' («i») = «timer.getElapsed» : «facIntResult»''')  
              i = i + 5  
        }  
        println("\nFactorial using Double")  
        // Benchmark Factorial using Double  
        i = 5  
        while (i < 55) {  
            timer.start  
            facDblResult = factorialDouble(i)  
            timer.stop
            println(''' («i») = «timer.getElapsed» : «facDblResult»''')  
            i = i + 5  
        }  
        println("\nFactorial using BigInteger")  
        // Benchmark Factorial using BigInteger  
        i = 5  
        while (i < 55) {  
            timer.start  
            facBigResult = factorialBigInteger(i)  
            timer.stop  
              println(''' («i») = «timer.getElapsed» : «facBigResult»''')  
            i = i + 5    
        }  
    }
    
    // Long Factorial    
    def static long factorialInt64(int n) {    
        if (n == 1)    
            return 1L  
        else    
            return n * factorialInt64(n - 1)  
    }  
      
    // Double Factorial
    def static double factorialDouble(int n) {    
        if (n == 1)    
            return 1d
        else    
            return n * factorialDouble(n - 1)  
    }  
      
    // BigInteger Factorial   
    def static BigInteger factorialBigInteger(int n) {    
        if (n == 1)    
            return 1BI  
        else    
            return BigInteger::valueOf(n) * factorialBigInteger(n - 1)  
    }  
}



And the Output is:

Sunday, May 6, 2012

Xtend - Basics by Example



Extending my Basics by Example series to a new language. today's version of the post written in Xtend.

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
// Xtend Basics
package com.series
import java.util.Calendar
import java.util.GregorianCalendar

public class Greet {
    // Fields or Attributes
    private String message  
    private String name
    private int loopMessage 
    // Getters and Setters. 
    // M7 will introduce annotation @Property to auto generate them (if not present)
    def public String getMessage() {  
        return this.message
    }  
    def public void setMessage(String value) {  
        this.message = this.capitalize(value)  
    }  
    def public String getName() {  
        return this.name
    }  
    def public void setName(String value) {  
        this.name = this.capitalize(value)  
    }  
    def public int getLoopMessage() {  
        return this.loopMessage  
    }  
    def public void setLoopMessage(int value) {  
        this.loopMessage = value  
    }  
    // Constructor  
    public new() {
        this.message = ""  
        this.name = ""
        this.loopMessage = 0           
    }
    // Overloaded Constructor  
    public new(String message, String name, int loopMessage) {  
        this.message = this.capitalize(message)  
        this.name = this.capitalize(name)  
        this.loopMessage = loopMessage  
    }    
    // Method 1  
    def private String capitalize(String value) {  
        // "if-then-else" statement  
        if (value.length() >= 1) {  
            return value.toFirstUpper()  
        }  
        else  {  
            return ""  
        }  
    }  
    // Method 2  
    def public void Salute() {  
        // "for (each)" statement
        for (int i : 0..this.loopMessage) {  
            println(this.message + " " + this.name + "!")  
        }  
    }  
    // Overloaded Method 2.1  
    def public void Salute(String message, String name, int loopMessage) {  
        // "while" statement  
        var int i = 0  
        while(i < loopMessage) {  
            println(this.capitalize(message) + " " + this.capitalize(name) + "!")
            i = i + 1
        }  
    }      
    // Overloaded Method 2.2  
    def public void Salute(String name) {  
        // "switch/case" statement  
        // doesn't work with iterables (i.e: case 6..11: ...)
        // doesn't allow multiple expressions in one case (i.e: case i>=6 && i<=11: ...)
        // doesn't allow fall through (i.e: case 6: case 7: case N: ...)
        // so better to use if-else-if expression instead
        var GregorianCalendar dtNow = new GregorianCalendar()        
        val int hh = dtNow.get(Calendar::HOUR_OF_DAY) 
        if (hh >= 6 && hh <= 11) this.message = "good morning,"        
        else if (hh >= 12 && hh <= 17) this.message = "good afternoon,"
        else if (hh >= 18 && hh <= 22) this.message = "good evening,"            
        else if (hh == 23 || (hh >= 0 && hh <= 5)) this.message = "good night,"
        else this.message = "huh?"        
        println(this.capitalize(this.message) + " " + this.capitalize(name) + "!")  
    }  
}
package com.series
import java.util.Scanner  
import java.lang.System 
// Greet Program
public class Program { 
    def public static void main(String[] args) {
        // Define variable object of type Greet and Instantiate. Call Constructor  
        val 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(), "xtend", g.getLoopMessage())  
        // Overloaded Method 2.2  
        g.Salute("carlos")
        
        // Stop and exit  
        println("Press any key to exit...")        
        val Scanner in = new Scanner(System::in)  
        val String line = in.nextLine()  
        in.close()                 
    }    
}

Greetings Program - Minimal
// Xtend Basics
import java.util.Calendar
import java.util.GregorianCalendar

class Greet {
    // Fields or Attributes
    private String message  
    private String name
    private int loopMessage    
    // Getters and Setters. 
    // M7 will introduce annotation @Property to auto generate them (if not present)    
    def getMessage() {  
        message
    }  
    def setMessage(String value) {  
        message = capitalize(value)  
    }  
    def getName() {  
        name
    }  
    def setName(String value) {  
        name = capitalize(value)  
    }  
    def getLoopMessage() {  
        loopMessage  
    }  
    def setLoopMessage(int value) {  
        loopMessage = value  
    }  
    // Constructor  
    new() {
        message = ""  
        name = ""
        loopMessage = 0           
    }
    // Overloaded Constructor  
    new(String message, String name, int loopMessage) {  
        this.message = capitalize(message)  
        this.name = capitalize(name)  
        this.loopMessage = loopMessage  
    }    
    // Method 1  
    def private String capitalize(String value) {  
        // "if-then-else" statement  
        if (value.length >= 1)  
            value.toFirstUpper  
        else    
            ""  
    }  
    // Method 2  
    def Salute() {  
        // "for (each)" statement
        for (i : 0..loopMessage) {  
            println(message + " " + name + "!")  
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(String message, String name, int loopMessage) {  
        // "while" statement  
        var i = 0  
        while(i < loopMessage) {  
            println(capitalize(message) + " " + capitalize(name) + "!")
            i = i + 1
        }  
    }      
    // Overloaded Method 2.2  
    def Salute(String name) {  
        // "switch/case" statement  
        // doesn't work with iterables (i.e: case 6..11: ...)
        // doesn't allow multiple expressions in one case (i.e: case i>=6 && i<=11: ...)
        // doesn't allow fall through (i.e: case 6: case 7: case N: ...)
        // so better to use if-else-if expression instead
        var dtNow = new GregorianCalendar        
        val hh = dtNow.get(Calendar::HOUR_OF_DAY) 
        if (hh >= 6 && hh <= 11) message = "good morning,"        
        else if (hh >= 12 && hh <= 17) message = "good afternoon,"
        else if (hh >= 18 && hh <= 22) message = "good evening,"            
        else if (hh == 23 || (hh >= 0 && hh <= 5)) message = "good night,"
        else message = "huh?"        
        println(capitalize(message) + " " + capitalize(name) + "!")  
    }  
}
import java.util.Scanner  
// Greet Program
class Program { 
    def static main(String[] args) {
        // Define variable object of type Greet and Instantiate. Call Constructor  
        val 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, "xtend", g.getLoopMessage)  
        // Overloaded Method 2.2  
        g.Salute("carlos")
        
        // Stop and exit  
        println("Press any key to exit...")        
        val in = new Scanner(System::in)  
        val line = in.nextLine  
        in.close
    }    
}


And the Output is:




Auto-Implemented Properties in Xtend

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the field. In Xtend you will use the @Property annotation which will generate a Java-Bean-style getter and setter (if the field is not final) for an annotated field and only generated when not explicitly defined.


// Xtend Basics  
class AutoImplementedProperties {  
    // Fields + Auto-Implemented Properties  
    @Property String message  
    @Property String name  
    @Property int loopMessage  
    // Methods  
    def salute() {    
        println('''«message.toFirstUpper» «name.toFirstUpper» «loopMessage»!''')
    }  
}
class Program { 
    def static void main(String[] args) {
        var g = new AutoImplementedProperties => [ 
            // Call Set Property  
            message = "hello"         
            name = "world"
            loopMessage = 5        
        ]
        // print them out  
        g.salute
        // and print them again using Get Properties  
        println('''«g.message» «g.name» «g.loopMessage»!''')
    }    
}

And the output is:


Sunday, April 22, 2012

OO Hello World - Xtend



The OO Hello World in Xtend, the "the CoffeScript for the JVM", is here!

Xtend is a statically-typed programming language which is tightly integrated with and
runs on the Java Virtual Machine.


You can see the OO Hello World series post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html where I give some details on why these "oo hello world series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
class Greet {
 String name
 new(String name) {
  this.name = name.toFirstUpper
 }
 def salute() {
  println("Hello " + name + "!")
 }
}
// Greet Program
class Program {
 def static void main(String[] args) {
  val g = new Greet("world")  
  g.salute
 } 
}

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

public class Greet {
 private String name
 public new(String name) {
  this.name = name.toFirstUpper()
 }
 def public void salute() {
  println("Hello " + this.name + "!")
 }
}
package com.series

// Greet Program
public class Program { 
 def public static void main(String[] args) {
  val g = new Greet("world")  
  g.salute()
 } 
}

The Program Output:








Xtend Info:

"Xtend is a statically-typed programming language developed at Eclipse.org. It
has a strong focus on leveraging all the good parts of Java, including seamless
integration with the huge amount of Java frameworks and libraries out there.” Taken from: ( Pragmatic Magazine - Issue 30, December 2011 )

Appeared:
2011
Current Version:
Developed by:
Eclipse
Creator:
Sven Efftinge, Sebastian Zarnekow
Influenced by:
Java (James Gosling)
Predecessor Language
N/A
Predecessor Appeared
N/A
Predecessor Creator
N/A
Runtime Target:
JVM
Latest Framework Target:
JDK 6,7
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.xtend”
Keywords:
41
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
N/A
Latest IDE Support:
Eclipse
Language Reference:
Extra Info:


Wednesday, April 18, 2012

Factorial and Fibonacci in Kotlin



Here below a little program in Kotlin that implements 2 classes (+ an extra utility Stopwatch class from my previous post http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one is the main function which has the execution entry point.

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members (or 2 separate classes in the case of Kotlin since it does not supports staitc methods in a class), and finally the third one that uses different return types (including java.math.BigInteger) for the Factorial method to compare the timing and result.

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

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


The Fiborial Program

// Factorial and Fibonacci in Kotlin
package com.series

import java.math.BigInteger
import com.series.Stopwatch

// Instance (Singleton) Class that works as a Module/Utils class
// static is not a class modifier in Kotlin
object StaticFiborial {
    // 'Static' Field
    private var className : String = "'Static' Constructor"
    // no available static __constructor support
    // Static Initializer Method instead, but need to be explicitly invoked
    fun constructor() {
        className = "'Static' Constructor";
        println(className)
    }
    // 'Static' Method - Factorial Recursive
    fun factorialR(n : Int) : BigInteger? {
        if (n == 1)
            return BigInteger.ONE
        else
            return BigInteger.valueOf(n.toLong())?.multiply(factorialR(n - 1))
    }
    // 'Static' Method - Factorial Imperative
    fun factorialI(var n : Int) : BigInteger? {
        var res: BigInteger? = BigInteger.ONE
        while (n > 1) {
            res = res?.multiply(BigInteger.valueOf(n.toLong()))
            n -= 1
        }
        return res
    }
    // 'Static' Method - Fibonacci Recursive
    fun fibonacciR(n : Int) : Long {
        if (n < 2)
            return 1
        else
            return fibonacciR(n - 1) + fibonacciR(n - 2)
    }
    // 'Static' Method - Fibonacci Imperative
    fun fibonacciI(n : Int) : Long {
        var pre : Long = 1
        var cur : Long = 1
        var tmp : Long
        for (i in 2..n) {
            tmp = cur + pre
            pre = cur
            cur = tmp
        }
        return cur
    }
    // 'Static' Method - Benchmarking Algorithms
    fun benchmarkAlgorithm(algorithm : Int, values : Array<Int>) {
        val timer : Stopwatch = Stopwatch()
        var testValue : Int
        var i : Int = 1
        var facTimeResult : BigInteger? = BigInteger.ZERO
        var fibTimeResult : Long

        when (algorithm) {
            1 -> {
                println("\nFactorial Imperative:");
                // "For" Loop Statement
                for (j in 1..values.size - 1) {
                    testValue = values[j]
                    // Taking Time
                    timer.start()
                    facTimeResult = factorialI(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                }
            }
            2 -> {
                println("\nFactorial Recursive:")
                // "While" Loop Statement
                while (i < values.size) {
                    testValue = values[i]
                    // Taking Time
                    timer.start()
                    facTimeResult = factorialR(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                    i += 1
                }
            }
            3 -> {
                println("\nFibonacci Imperative:")
                // "Do-While" Loop Statement
                do {
                    testValue = values[i]
                    // Taking Time
                    timer.start()
                    fibTimeResult = fibonacciI(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                    i++
                } while (i < values.size)
            }
            4 -> {
                println("\nFibonacci Recursive:")
                // "For Each" Loop Statement
                for (j in values) {
                    testValue = j
                    // Taking Time
                    timer.start()
                    fibTimeResult = fibonacciR(testValue)
                    timer.stop()
                    // Getting Time
                    println(" (${testValue}) = ${timer.getElapsed()}")
                }
            }
            else -> println("DONG!")
        }
    }
}

// Instance Class
// Instance Field
class InstanceFiborial(private var className : String) {
    // Instance Constructor
    this() : this("Instance Constructor") {
        println(this.className)
    }
    // Instance Method - Factorial Recursive
    fun factorialR(n : Int) : BigInteger? {
        // Calling Static Method
        return StaticFiborial.factorialR(n)
    }
    // Instance Method - Factorial Imperative
    fun factorialI(n : Int) : BigInteger? {
        // Calling Static Method
        return StaticFiborial.factorialI(n)
    }
    // Instance Method - Fibonacci Recursive
    fun fibonacciR(n : Int) : Long {
        // Calling Static Method
        return StaticFiborial.fibonacciR(n)
    }
    // Instance Method - Fibonacci Imperative
    fun fibonacciI(n : Int) : Long {
        // Calling Static Method
        return StaticFiborial.fibonacciI(n)
    }
}

fun main(args: Array<String>) {
    println("\n'Static' Class");
    // Calling 'Static' Class and Methods
    // No instantiation needed. Calling method directly from the class
    StaticFiborial.constructor()
    println("FacImp(5) = ${StaticFiborial.factorialI(5)}")
    println("FacRec(5) = ${StaticFiborial.factorialR(5)}")
    println("FibImp(11)= ${StaticFiborial.fibonacciI(11)}")
    println("FibRec(11)= ${StaticFiborial.fibonacciR(11)}")

    println("\nInstance Class");
    // Calling Instance Class and Methods
    // Need to instantiate before using. Call method from instantiated object
    val ff = InstanceFiborial()
    println("FacImp(5) = ${ff.factorialI(5)}")
    println("FacRec(5) = ${ff.factorialR(5)}")
    println("FibImp(11)= ${ff.fibonacciI(11)}")
    println("FibRec(11)= ${ff.fibonacciR(11)}")

    // Create a (generic) list of integer values to test
    // From 5 to 50 by 5
    val values = Array<Int>(11, {i -> i * 5})

    // Benchmarking Fibonacci
    // 1 = Factorial Imperative
    StaticFiborial.benchmarkAlgorithm(1, values)
    // 2 = Factorial Recursive
    StaticFiborial.benchmarkAlgorithm(2, values)

    // Benchmarking Factorial
    // 3 = Fibonacci Imperative
    StaticFiborial.benchmarkAlgorithm(3, values)
    // 4 = Fibonacci Recursive
    StaticFiborial.benchmarkAlgorithm(4, values)

    // Stop and exit
    println("Press any key to exit...")
    //val ins: Scanner = Scanner(System.in)
    //var line: String? = ins.nextLine()
    //ins.close()
}

And the Output is:



























































Printing the Factorial and Fibonacci Series
package com.series

import java.math.BigInteger
import java.lang.StringBuffer

object Fiborial {
    // Using a StringBuffer as a list of string elements
    fun getFactorialSeries(n : Int) : String? {
        val series = StringBuffer()
        // We begin by concatenating the number you want to calculate
        // in the following format: "!# ="
        series.append("!")
        series.append(n)
        series.append(" = ")
        // We iterate backwards through the elements of the series
        // Reversed ranges are not supported... using while instead
        //for (i in n..0) {
        var i : Int = n
        while (i > 0) {
            // and append it to the list
            series.append(i)
            if (i > 1)
                series.append(" * ")
            else
                series.append(" = ")
            i--
        }
        // Get the result from the Factorial Method
        // and append it to the end of the list
        series.append(factorial(n))
        return series.toString()
    }

    // Using a StringBuffer as a list of string elements
    fun getFibonnaciSeries(n : Int) : String? {
        // Create the String that will hold the list
        val series = StringBuffer()
        // We begin by concatenating the first 3 values which
        // are always constant
        series.append("0, 1, 1")
        // Then we calculate the Fibonacci of each element
        // and add append it to the list
        for (i in 2..n) {
            if (i < n)
                series.append(", ")
            else
                series.append(" = ")
            series.append(fibonacci(i))
        }
        // return the list as a string
        return series.toString()
    }

    fun factorial(n : Int) : BigInteger? {
        if (n == 1)
            return BigInteger.ONE
        else
            return BigInteger.valueOf(n.toLong())?.multiply(factorial(n - 1))
    }

    fun fibonacci(n : Int) : Long {
        if (n < 2)
            return 1
        else
            return fibonacci(n - 1) + fibonacci(n - 2)
    }
}

fun main(args : Array<String>) {
    // Printing Factorial Series
    println("")
    println(Fiborial.getFactorialSeries(5))
    println(Fiborial.getFactorialSeries(7))
    println(Fiborial.getFactorialSeries(9))
    println(Fiborial.getFactorialSeries(11))
    println(Fiborial.getFactorialSeries(40))
    // Printing Fibonacci Series
    println("")
    println(Fiborial.getFibonnaciSeries(5))
    println(Fiborial.getFibonnaciSeries(7))
    println(Fiborial.getFibonnaciSeries(9))
    println(Fiborial.getFibonnaciSeries(11))
    println(Fiborial.getFibonnaciSeries(40))
}

And the Output is:


























Mixing Instance and Static Members in the same Class

Normally, instance classes can contain both, instance and static members such as: fields, getters, constructors/initializers, methods, etc. However, In Kotlin, unlike Java, classes do not have static methods, so it doesn't support mixing both of them on the same object or class. In the following code I had to create one Object and one Class to build this example.

package com.series

// 'Static' Class
object StaticFiborial {
    // 'Static' Field/Property
    private var _staticCount : Int = 0
    // 'Static' Read-Only Property
    public val StaticCount : Int
        get() {
            return _staticCount
        }
    // 'Static' Constructor
    //this() : this() {
    // No constructor support for Objects - failed to get descriptor for secondary constructor
    // using an explicit initializer method instead
    fun constructor() {
        println("\nStatic Constructor ${_staticCount}")
    }
    // 'Static' Method
    fun fibonacci(n : Int) {
        _staticCount += 1
        println("\nFibonacci(${n})")
    }
}

// Instance Class
// Instance Field/Property
class InstanceFiborial(private var _instanceCount : Int) {
    // Instance Read-Only Property
    public val InstanceCount : Int
        get() {
            return this._instanceCount
        }
    // Instance Constructor
    this() : this(0) {
        println("\nInstance Constructor ${this._instanceCount}")
    }
    // Instance Method
    fun factorial(n : Int) {
        this._instanceCount += 1
        println("\nFactorial(${n})")
    }
}

fun main(args : Array<String>) {
    // Calling Static Constructor and Methods
    // No need to instantiate
    StaticFiborial.constructor()
    StaticFiborial.fibonacci(5)

    // Calling Instance Constructor and Methods
    // Instance required
    val fib = InstanceFiborial()
    fib.factorial(5)

    StaticFiborial.fibonacci(15)
    fib.factorial(5)

    // Calling Instance Constructor and Methods
    // for a second object
    val fib2 = InstanceFiborial()
    fib2.factorial(5)

    println("")
    // Calling Static Property
    println("Static Count = ${StaticFiborial.StaticCount}")
    // Calling Instance Property of object 1 and 2
    println("Instance 1 Count = ${fib.InstanceCount}")
    println("Instance 2 Count = ${fib2.InstanceCount}")
}

And the Output is:



























Factorial using java.lang.Long, java.lang.Double, java.math.BigInteger


package com.series

import java.math.BigInteger
import com.series.Stopwatch

// Long Factorial
fun factorialInt64(n : Int) : Long {
    if (n == 1)
        return 1
    else
        return n * factorialInt64(n - 1)
}

// Double Factorial
fun factorialDouble(n : Int) : Double {
    if (n == 1)
        return 1.0
    else
        return n * factorialDouble(n - 1)
}

// BigInteger Factorial
fun factorialBigInteger(n : Int) : BigInteger? {
    if (n == 1)
        return BigInteger.ONE
    else
        return BigInteger.valueOf(n.toLong())?.multiply(factorialBigInteger(n - 1))
}

fun main(args: Array<String>) {
    val timer = Stopwatch()
    var facIntResult : Long = 0
    var facDblResult : Double = 0.0
    var facBigResult = BigInteger.ZERO

    println("\nFactorial using Int64")
    // Benchmark Factorial using Int64
    var i = 5
    while (i < 55) {
        timer.start()
        facIntResult = factorialInt64(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facIntResult}")
        i += 5
    }
    println("\nFactorial using Double")
    // Benchmark Factorial using Double
    i = 5
    while (i < 55) {
        timer.start()
        facDblResult = factorialDouble(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facDblResult}")
        i += 5
    }
    println("\nFactorial using BigInteger")
    // Benchmark Factorial using BigInteger
    i = 5
    while (i < 55) {
        timer.start()
        facBigResult = factorialBigInteger(i)
        timer.stop()
        println(" (${i}) = ${timer.getElapsed()} : ${facBigResult}")
        i += 5
    }
}

And the Output is: