Showing posts with label Cobra. Show all posts
Showing posts with label Cobra. Show all posts

Tuesday, November 19, 2013

Arrays and Indexers in Cobra



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

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

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

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


use System.Text

namespace CobraArrays

class Program is public
    shared   
        def main
            # Single-dimensional Array(s)  
            .printTitle("Reverse Array Elements")
            
            # Declare and initialize Array of Chars 
            letters as char[] = char[](5)
            letters[0] = c'A'  
            letters[1] = c'E'  
            letters[2] = c'I'  
            letters[3] = c'O'  
            letters[4] = c'U'
            
            .printArrayChar(letters)  
            inverse_letters as char[] = .reverseChar(letters)  
            .printArrayChar(inverse_letters)
        
            .printTitle("Sort Integer Array Elements")  

            # Declare and Initialize Array of Integers  
            numbers as int[] = @[10, 8, 3, 1, 5]
            .printArrayInt(numbers)  
            ordered_numbers as int[] = .bubblesortInt(numbers)  
            .printArrayInt(ordered_numbers)  

            .printTitle("Sort String Array Elements")  

            # Declare and Initialize and Array of Strings  
            names as String[] = @[   
                'Damian', 
                'Rogelio',   
                'Carlos', 
                'Luis', 
                'Daniel'  
            ]  
            .printArrayString(names)  
            ordered_names as String[] = .bubblesortString(names)  
            .printArrayString(ordered_names)  

            # Multi-dimensional Array (Matrix row,column) 
            # Cobra does not support multi-dimensional arrays syntax            
            # using List<of List<of Type>> instead
            .printTitle("Transpose Matrix")  

            /# Matrix row=2,col=3   
            # A =  [6  4 24]   
            #      [1 -9  8]   
            #/               
            matrix as List<of List<of int>> = [[6, 4, 24],
                                                [1, -9, 8]]            

            .printMatrix(matrix)  
            transposed_matrix as List<of List<of int>> = .transposeMatrix(matrix)  
            .printMatrix(transposed_matrix)  
        
            # Jagged Array (Array-of-Arrays)  
            .printTitle("Upper Case Random Array & Graph Number of Elements")  

            /#               
            # Creating an array of string arrays using the String.Split method  
            # instead of initializing it manually as follows:  
            #   
            # text as String[] = @[   
            #      @[ 'word1', 'word2', 'wordN' ],   
            #      @[ 'word1', 'word2', 'wordM' ],   
            #      ...  
            #      ]  
            #   
            # Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"  
            #   
            #/  
            text = [ _
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(c' '),   
            "los obstáculos más grandes, nuestras propias indecisiones;".split(c' '),
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(c' '),
            "la cosa más fácil, equivocarnos;".split(c' '),
            "la más destructiva, la mentira y el egoísmo;".split(c' '),
            "la peor derrota, el desaliento;".split(c' '),
            "los defectos más peligrosos, la soberbia y el rencor;".split(c' '),
            "las sensaciones más gratas, la buena conciencia...".split(c' ')
            ]
            
            .printJaggedArray(text)  
            /#
            .uppercaserandomArray(text)  
            #/
            .printJaggedArray(text)  
            .graphJaggedArray(text)  
            
            # Array Exceptions  
            .printTitle("Common Array Exceptions")  

            .printCommonArrayExceptions(nil)  
            .printCommonArrayExceptions(text)  

            # Accessing Class Array Elements through Indexer      
            .printTitle("Alphabets")  
            
            vowels as Alphabet = Alphabet(5)  
            vowels[0] = c'a'  
            vowels[1] = c'e'  
            vowels[2] = c'i'  
            vowels[3] = c'o'  
            vowels[4] = c'u'  

            print "\nVowels = {" + [vowels[0], vowels[1], vowels[2], 
                                vowels[3], vowels[4]].join(",") + "}"  

            en as Alphabet = Alphabet("abcdefghijklmnopqrstuvwxyz")  
            print "English Alphabet = {[en.toString]}"  

            print "Alphabet Extract en\[9..19\] = {[Alphabet(en.slice(9, 10))]}"

            word1 as String = [en[6], en[14], en[14], en[3]].join('')  
            word2 as String = [en[1], en[24], en[4]].join('')
            word3 as String = [en[4], en[21], en[4], en[17], en[24],   
                                en[14], en[13], en[4]].join('')
            print "\n[word1] [word2], [word3]!"  

            Console.read
        
        def reverseChar(arr as char[]) as char[]
            reversed as char[] = char[](arr.length)  
            i as int = 0  
            for j in arr.length-1:-1:-1
                reversed[i] = arr[j]  
                i += 1
            return reversed
            
        def bubblesortInt(arr as int[]) as int[]  
            swap as int = 0  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j] > arr[j + 1]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
            
        def bubblesortString(arr as String[]) as String[]
            swap as String = ""  
            for i in arr.length-1:-1:-1  
                for j in arr.length-1
                    if arr[j][0] > arr[j + 1][0]
                        swap = arr[j]  
                        arr[j] = arr[j + 1]  
                        arr[j + 1] = swap  
            return arr 
        
        def transposeMatrix(m as List<of List<of int>>) as List<of List<of int>>
            /# Transposing a Matrix 2,3   
            #   
            # A =  [6  4 24]T [ 6  1]   
            #      [1 -9  8]  [ 4 -9]  
            #                 [24  8]  
            #/ 
            transposed = [[0]] # to get [int] instead of [object]
            transposed.clear
            for i in 0:m[0].count
                transposed.add([0]) # same here
                transposed[i].clear
                for j in 0:m.count    
                    transposed[i].add(m[j][i])
            return transposed        
        
        def printArrayChar(arr as char[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
                
        def printArrayInt(arr as int[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printArrayString(arr as String[]) 
            print "\nPrint Array Content " + arr.getType.name.replace(']', _
                arr.length.toString + ']')
            for i in arr.length
                print " array " + String.format("[[{0,2}]] = {1,2}", i, arr[i])
        
        def printMatrix(m as List<of List<of int>>)
            print "\nPrint Matrix Content " + m.getType.name 
            for i in 0:m.count 
                for j in 0:m[0].count  
                    print " array " + String.format("[[{0,2},{1,2}]] = {2,2} " _ 
                        , i, j, m[i][j])
        
        def graphJaggedArray(arr as List<of String[]?>)  
            /# When using Arrays, we can use for(each) instead of for by index:         
            #    
            # for s in arr: 
            #   for w as String in s 
            #    
            #/  
            print "\nPrint Text Content [arr.getType.name]"  
            for i in arr.count  
                Console.write("Line{0,2}|", i+1)
                for j in arr[i].length  
                    Console.write("{0,3}", "*")
                print " ([arr[i].length.toString])"  
        
        def printJaggedArray(arr as List<of String[]?>)  
            line as StringBuilder?      
            print "\nPrint Jagged Array Content [arr.getType.name]"
            for i in arr.count
                line = StringBuilder() 
                for j in arr[i].length
                    line.append(" " + arr[i][j])
                if line.toString == line.toString.toUpper  
                    line.append(r" <-- [UPPERCASED]")  
                print line.toString
        
        def printCommonArrayExceptions(arr as List<of String[]?>?)  
            try  
                arr[100][100] = "hola"    
            catch ex as Exception      
                print "\nException: \n[ex.getType.name]\n[ex.message]"  
        
        def printTitle(message as String) 
            print ""
            print "======================================================"
            print message
            print "======================================================"
    
class Alphabet is public
    # Array Field
    var _letters as char[]? is private
    
    # Indexer Get/Set Property  
    pro [index as int] as char is public
        get
            return _letters[index]
        set
            _letters[index] = value.toUpper
            
    # Read-Only Property  
    get length as int is public
        return _letters.length
    
    # Constructors
    cue init(size as int) is public  
        base.init  
        _letters = char[](size)
    
    cue init(list as String) is public
        base.init
        _letters = list.toUpper.toCharArray
    
    cue init(list as char[]) is public
        base.init
        _letters = list
    
    # Overridden Method    
    def toString as String is override
        return "" + _letters.join(',')

    # Method 
    def slice(start as int, length as int) as char[]?
        return _letters[start:start+length]


The output:






















































































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

Thursday, June 2, 2011

Factorial and Fibonacci in Cobra



Here below a little program in Cobra that implements 2 classes (in fact, they are 3). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

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

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

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


The Fiborial Program

# Factorial and Fibonacci in Cobra  
use System.Collections.Generic  
use System.Diagnostics  
use System.Numerics  

namespace FiborialCobra
  
    # Static Class
    class StaticFiborial is public
        shared
            # Static Field  
            var __className as String  
            # Static Constructor  
            cue init
                __className = 'Static Constructor'
                print '[__className]'
            # Static Method - Factorial Recursive    
            def factorialR(n as int) as BigInteger is public
                if n == 1 
                    return BigInteger.one
                else                        
                    return BigInteger.multiply(BigInteger(n), .factorialR(n - 1))
            # Static Method - Factorial Imperative    
            def factorialI(n as int) as BigInteger is public                
                res as BigInteger = BigInteger.one
                for i as int in n:0:-1
                    res = BigInteger.multiply(res, BigInteger(i))
                return res
            # Static Method - Fibonacci Recursive    
            def fibonacciR(n as int) as int64 is public
                if n < 2  
                    return 1
                else    
                    return .fibonacciR(n - 1) + .fibonacciR(n - 2)  
            # Static Method - Fibonacci Imperative  
            def fibonacciI(n as int) as int64 is public  
                pre as int64 = 1  
                cur as int64 = 1  
                tmp as int64 = 0  
                for i as int in 2:n+1
                    tmp = cur + pre
                    pre = cur  
                    cur = tmp  
                    i=i # ignore compiler warning
                return cur
            # Static Method - Benchmarking Algorithms  
            def benchmarkAlgorithm(algorithm as int, values as List<of int>) is public  
                timer as Stopwatch = Stopwatch()  
                i as int = 0
                testValue as int = 0  
                facTimeResult as BigInteger = BigInteger.zero                
                fibTimeResult as int64 = 0
                facTimeResult = facTimeResult
                fibTimeResult = fibTimeResult
                
                # "if-elif-else" Flow Control Statement
                if algorithm == 1  
                    print '\nFactorial Imperative:'
                    # "For in range" Loop Statement   
                    for i as int in values.count                  
                        testValue = values[i]
                        # Taking Time    
                        timer.start  
                        facTimeResult = .factorialI(testValue)  
                        timer.stop
                        # Getting Time    
                        print ' ([testValue]) = [timer.elapsed]'
                else if algorithm == 2  
                    print '\nFactorial Recursive:'
                    # "While" Loop Statement  
                    while i < values.count
                        testValue = values[i]  
                        # Taking Time    
                        timer.start
                        facTimeResult = .factorialR(testValue)
                        timer.stop
                        # Getting Time    
                        print ' ([testValue]) = [timer.elapsed]'
                        i += 1  
                else if algorithm == 3
                    print "\nFibonacci Imperative:"   
                    # "Do-While" Loop Statement  
                    post while i < values.count
                        testValue = values[i]  
                        # Taking Time  
                        timer.start
                        fibTimeResult = .fibonacciI(testValue)  
                        timer.stop  
                        # Getting Time  
                        print ' ([testValue]) = [timer.elapsed]'
                        i += 1  
                else if algorithm == 4  
                    print "\nFibonacci Recursive:"  
                    # "For in List" Loop Statement   
                    for i as int in values.count
                        testValue = values[i]
                        # Taking Time  
                        timer.start 
                        fibTimeResult = .fibonacciR(testValue)  
                        timer.stop
                        # Getting Time  
                        print ' ([testValue]) = [timer.elapsed]'
                else  
                    print 'DONG!'

    # Instance Class  
    class InstanceFiborial is public
        # Instances Field  
        var __className as String  
        # Instance Constructor  
        cue init  
            base.init
            __className = "Instance Constructor"  
            print __className  
        # Instance Method - Factorial Recursive  
        def factorialR(n as int) as BigInteger is public 
            # Calling Static Method  
            return StaticFiborial.factorialR(n)  
        # Instance Method - Factorial Imperative  
        def factorialI(n as int) as BigInteger is public 
            # Calling Static Method  
            return StaticFiborial.factorialI(n)  
        # Instance Method - Fibonacci Recursive    
        def fibonacciR(n as int) as int64 is public
            # Calling Static Method  
            return StaticFiborial.fibonacciR(n)  
        # Instance Method - Fibonacci Imperative  
        def fibonacciI(n as int) as int64 is public  
            # Calling Static Method  
            return StaticFiborial.fibonacciI(n)  
                    
    # Console Program  
    class Program is public  
        def main is shared 
            print '\nStatic Class'  
            # Calling Static Class and Methods  
            # No instantiation needed. Calling method directly from the class  
            print 'FacImp(5) = [StaticFiborial.factorialI(5)]'  
            print 'FacRec(5) = [StaticFiborial.factorialR(5)]'  
            print 'FibImp(11)= [StaticFiborial.fibonacciI(11)]'  
            print 'FibRec(11)= [StaticFiborial.fibonacciR(11)]'  
          
            print '\nInstance Class'  
            # Calling Instance Class and Methods  
            # Need to instantiate before using. Call method from instantiated obj  
            ff as InstanceFiborial = InstanceFiborial()
            print 'FacImp(5) = [ff.factorialI(5)]'  
            print 'FacRec(5) = [ff.factorialR(5)]'  
            print 'FibImp(11)= [ff.fibonacciI(11)]'  
            print 'FibRec(11)= [ff.fibonacciR(11)]'  
          
            # Create a List of integer values to test  
            # From 5 to 50 by 5  
            values as List<of int> = List<of int>()  
            for i as int in 5:55:5
                values.add(i)

            # 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  
            Console.read

And the Output is:






































Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

Printing the Factorial and Fibonacci Series
use System.Text  
use System.Numerics  

namespace FiborialSeries   
    # Instance Class    
    class Fiborial is public
        shared
            # Using a StringBuilder as a list of string elements    
            def getFactorialSeries(n as int) as String is public
                # Create the String that will hold the list    
                series as StringBuilder = StringBuilder()   
                # We begin by concatenating the number you want to calculate    
                # in the following format: '!# ='    
                series.append('!')  
                series.append(n)  
                series.append(' = ')  
                # We iterate backwards through the elements of the series    
                for i as int in n:0:-1  
                    # and append it to the list    
                    series.append(i)  
                    if i > 1   
                        series.append(' * ')    
                    else  
                        series.append(' = ')  
                # 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 StringBuilder as a list of string elements    
            def getFibonnaciSeries(n as int) as String is public
                # Create the String that will hold the list
                series as StringBuilder = 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 as int in 2:n+1
                    if i < n  
                        series.append(', ')   
                    else
                        series.append(' = ')    
                    series.append(.fibonacci(i))  
                # return the list as a string    
                return series.toString 
                  
            def factorial(n as int) as BigInteger is public
                if n == 1
                    return BigInteger.one
                else
                    return BigInteger.multiply(BigInteger(n), .factorial(n - 1))
              
            def fibonacci(n as int) as int64 is public
                if n < 2
                    return 1    
                else    
                    return .fibonacci(n - 1) + .fibonacci(n - 2)  
      
    # Console Program  
    class Program is public  
        def main is shared 
            # Printing Factorial Series    
            print ''  
            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)  
              
            Console.read

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, properties, constructors, methods, etc.

namespace FiborialExtrasCobra2  
      
    # Instance Classes can have both: static and instance members.
          
    # Instance Class    
    class Fiborial is public  
        # Instance Field  
        var __instanceCount as int
        # Static Field  
        var __staticCount as int is shared 
        # Instance Read-Only Property            
        pro instanceCount as int is public  
            get  
                return __instanceCount          
        # Static Read-Only Property    
        # Remeber that Properties are Methods to the CLR, so, 
        # you can also define static properties for static fields.             
        pro staticCount as int is shared, public
            get    
                return __staticCount    
        # Instance Constructor    
        cue init
            base.init
            __instanceCount = 0
            print '\nInstance Constructor [__instanceCount]'  
        # Static Constructor    
        cue init is shared        
            __staticCount = 0    
            print '\nStatic Constructor [__staticCount]'
        # Instance Method  
        def factorial(n as int) is public
            __instanceCount += 1   
            print '\nFactorial([n])'   
        # Static Method    
        def fibonacci(n as int) is shared, public
            __staticCount += 1  
            print '\nFibonacci([n])'   
      
    # Console Program  
    class Program is public
        def main is shared     
            # Calling Static Constructor and Methods    
            # No need to instantiate    
            Fiborial.fibonacci(5)  
              
            # Calling Instance Constructor and Methods    
            # Instance required    
            fib as Fiborial = Fiborial()    
            fib.factorial(5)  
              
            Fiborial.fibonacci(15)  
            fib.factorial(5)  
              
            # Calling Instance Constructor and Methods    
            # for a second object    
            fib2 as Fiborial = Fiborial()  
            fib2.factorial(5)  
              
            print ''  
            # Calling Static Property    
            print 'Static Count = [Fiborial.staticCount]'  
            # Calling Instance Property of object 1 and 2    
            print 'Instance 1 Count = [fib.instanceCount]'  
            print 'Instance 2 Count = [fib2.instanceCount]'  
            Console.read

And the Output is:























Factorial using System.Int64, System.Double/Float, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET, JScript.NET, Boo execution thrown an Overflow Exception when using the "Long/long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just "tried" to say, lets have a look at the following code and the output we get.

use System.Diagnostics  
use System.Numerics  

namespace FiborialExtrasCobra3  

    class FiborialExtrasProgram 
        shared            

            def main
                timer as Stopwatch = Stopwatch()  
                facIntResult as int64 = 0  
                facDblResult as float = 0  
                facBigResult as BigInteger = BigInteger.zero
                i as int = 0
                  
                print '\nFactorial using Int64'  
                # Benchmark Factorial using Int64                    
                for i as int in 5:55:5  
                    timer.start
                    facIntResult = .factorialInt64(i)  
                    timer.stop         
                    print ' ([i]) = [timer.elapsed] : [facIntResult]'  
                  
                print '\nFactorial using Float'  
                # Benchmark Factorial using float  
                for i as int in 5:55:5  
                    timer.start
                    facDblResult = .factorialFloat(i)  
                    timer.stop         
                    print ' ([i]) = [timer.elapsed] : [facDblResult]'  
                  
                print '\nFactorial using BigInteger'  
                # Benchmark Factorial using BigInteger  
                for i as int in 5:55:5  
                    timer.start
                    facBigResult = .factorialBigInteger(i)  
                    timer.stop         
                    print ' ([i]) = [timer.elapsed] : [facBigResult]'  
                  
                Console.read
                
            # Long Factorial  
            def factorialInt64(n as int) as int64
                if n == 1  
                    return 1  
                else  
                    return n * .factorialInt64(n - 1)  
                  
            # float/Number Factorial     
            def factorialFloat(n as int) as float
                if n == 1  
                    return 1  
                else  
                    return n * .factorialFloat(n - 1)  
               
            # BigInteger Factorial     
            def factorialBigInteger(n as int) as BigInteger   
                if n == 1  
                    return BigInteger.one  
                else  
                    return BigInteger.multiply(BigInteger(n), .factorialBigInteger(n - 1))

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

And the Output is:

Saturday, October 23, 2010

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

Friday, July 2, 2010

OO Hello World - Cobra



Hello world in Cobra is here! Another Python – Like language which has lots of built in cool features such as Unit Tests and Contracts.


NOTE: The indentation appears to be 1 space when it should be 4. Cobra won't accept anything other than 4 (or one tab per indent). Take it in consideration if you want to test the code :)


By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.

class Greet
 var name
 
 cue init(name as String)
   base.init
   #.name = name[0].toString.toUpper + name[1:]
   .name = name.capitalized
  
  def salute
   print "Hello [.name]!"

# Greet the world!
class GreetProgram
  def main
   g = Greet("world")
   g.salute

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

use System
namespace _GreetProgram

 class Greet
  var name as String
  
  cue init(name as String)
   base.init
   #.name = name[0].toString.toUpper + name[1:]
   .name = name.capitalized
  
  def salute
   print "Hello [.name]!"


use _GreetProgram
 
# Greet the world!
 class GreetProgram
  def main is shared
   g = Greet("world")
   g.salute

The Program Output:









Cobra Info:
“Cobra is a general purpose programming language with: a clean, high-level syntax, static and dynamic binding, first class support for unit tests and contracts, compiled performance with scripting conveniences, lambdas and closures, extensions and mixins... and more” Taken from: (http://cobra-language.com/)

Appeared:
2006
Current Version:
Developed by:
Chuck Esterbrook
Creator:
Chuck Esterbrook
Influenced by:
Python (Guido van Rossum), C# (Anders Hejlsberg), Eiffel (Bertrand Meyer), Objective-C (Tom Love, Brad Cox)
Predecessor Language
Predecessor Appeared
Predecessor Creator
Runtime Target:
CLR
Latest Framework Target:
2.0
Mono Target:
Yes
Allows Unmanaged Code:
No
Source Code Extension:
“.cobra”
Keywords:
139 (including types)
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
No
Latest IDE Support:
SharpDevelop
MonoDevelop
VisualStudio
Language Reference:
Extra Info: