Showing posts with label Gosu. Show all posts
Showing posts with label Gosu. Show all posts

Thursday, December 4, 2014

Arrays and Indexers in Gosu



Today's post is about Arrays and Indexers in Gosu. 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 Gosu, 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 (not so) recent post (anymore), "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 Java 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.


package gosuarrays
uses java.lang.Character
uses java.lang.Integer
uses java.util.Random
uses java.lang.System
uses java.lang.StringBuffer
uses java.lang.Exception
uses java.util.Arrays

// Single-dimensional Array(s)
printTitle("Reverse Array Elements")

// Declare and Initialize Array of Chars
var letters = new Character[5]
letters[0] = 'A'
letters[1] = 'E'
letters[2] = 'I'
letters[3] = 'O'
letters[4] = 'U'

printArrayChar(letters)
var inverse_letters = reverseChar(letters)
printArrayChar(inverse_letters)

printTitle("Sort Integer Array Elements")

// Declare and Initialize Array of Integers
var numbers: Integer[] = {10, 8, 3, 1, 5}
printArrayInt(numbers)

var ordered_numbers = bubbleSortInt(numbers)
printArrayInt(ordered_numbers)

printTitle("Sort String Array Elements");

// Declare and Initialize and Array of Strings
var names = new String[] {
    "Damian",
    "Rogelio",
    "Carlos",
    "Luis",
    "Daniel"
}
printArrayString(names)
var ordered_names = bubbleSortString(names)
printArrayString(ordered_names)

// Multi-dimensional Array (Matrix row,column)

printTitle("Transpose Matrix")

/* Matrix row=2,col=3
         * A =  [6  4 24]
         *      [1 -9  8]
        */
var matrix: Integer[][] = {{ 6, 4, 24 },
                           { 1, -9, 8 }}
printMatrix(matrix)
var transposed_matrix = transposeMatrix(matrix)
printMatrix(transposed_matrix)

// Jagged Array (Array-of-Arrays)

printTitle("Upper Case Random Array & Graph Number of Elements")

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

// Array Exceptions

printTitle("Common Array Exceptions")

printCommonArrayExceptions(null)
printCommonArrayExceptions(text)

// Accessing Class Array Elements through Indexer

printTitle("Alphabets")

var vowels = new Alphabet(5)
vowels.setAt(0, 'a')
vowels.setAt(1, 'e')
vowels.setAt(2, 'i')
vowels.setAt(3, 'o')
vowels.setAt(4, 'u')

print("\nVowels = {${{vowels.getAt(0), vowels.getAt(1), vowels.getAt(2), vowels.getAt(3), vowels.getAt(4)}.join(",")}}")

var en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
print("English Alphabet = {${en.toString()}}")

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

var word1 = {en.getAt(6), en.getAt(14), en.getAt(14), en.getAt(3)}.toTypedArray().join("")
var word2 = {en.getAt(1), en.getAt(24), en.getAt(4)}.toTypedArray().join("")
var word3 = {en.getAt(4), en.getAt(21), en.getAt(4), en.getAt(17),
             en.getAt(24), en.getAt(14), en.getAt(13), en.getAt(4)}.toTypedArray().join("")

print("\n${word1} ${word2}, ${word3}!")


function reverseChar(arr: Character[]): Character[] {
  var reversed = new Character[arr.length]
  for (c in arr index i) {
    reversed[i] = c
  }
  return reversed
}

function bubbleSortInt(arr: Integer[]): Integer[] {
  var swap: int = 0
  for (i in arr.length|..0) {
    for (j in 0..|i) {
      if (arr[j] > arr[j + 1]) {
        swap = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = swap
      }
    }
  }
  return arr
}

function bubbleSortString(arr: String[]): String[] {
  var swap = ""
  for (i in arr.length|..0) {
    for (j in 0..|i) {
      if (arr[j][0] > arr[j + 1][0]) {
        swap = arr[j]
        arr[j] = arr[j + 1]
        arr[j + 1] = swap
      }
    }
  }
  return arr
}

function transposeMatrix(m: Integer[][]): Integer[][] {
  /* Transposing a Matrix 2,3
   *
   * A =  [6  4 24]T [ 6  1]
   *      [1 -9  8]  [ 4 -9]
   *                 [24  8]
  */
  var transposed = new Integer[m[0].length][m.length]
  for (i in 0..|m.length) {
    for (j in 0..|m[0].length) {
      transposed[j][i] = m[i][j]
    }
  }
  return transposed
}

function upperCaseRandomArray(arr: String[][]) {
  var r = new Random()
  var i = r.nextInt(arr.length)
  for (j in 0..|arr[i].length) {
    arr[i][j] = arr[i][j].toUpperCase()
  }
}

function printArrayChar(arr: Character[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${String.valueOf(arr[i]).leftPad(2)}")
  }
}

function printArrayInt(arr: Integer[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${String.valueOf(arr[i]).leftPad(2)}")
  }
}

function printArrayString(arr: String[]) {
  print("\nPrint Array Content ${arr.Class.Name} [${arr.length}]")

  for (i in 0..|arr.length) {
    print(" array [${String.valueOf(i).leftPad(2)}] = ${arr[i].leftPad(2)}")
  }
}

function printMatrix(m: Integer[][]) {
  print("\nPrint Matrix Content ${m.Class.Name}[${m.length},${m[0].length}]")

  for (i in 0..|m.length) {
    for (j in 0..|m[0].length) {
      print(" array [${String.valueOf(i).leftPad(2)},${String.valueOf(i).leftPad(2)}] = ${m[i][j].toString().leftPad(2)}")
    }
  }
}

function graphJaggedArray(arr: String[][]) {
  /* When using Arrays, we can use foreach instead of for:
   *
   * for (i in 0..|arr.length)
   *   for (j in 0..|arr.length)
   *
  */
  print("\nPrint Text Content " + arr.Class.Name)
  var lineCount = 1
  for(s in arr) {
    System.out.print("Line${String.valueOf(lineCount).leftPad(2)}|")
    for(w in s) {
      System.out.print("*".leftPad(3))
    }
    print(" (${s.length})")
    lineCount++
  }
}

function printJaggedArray(arr: String[][]) {
  var line: StringBuffer
  print("\nPrint Jagged Array Content " + arr.Class.Name)
  for (i in 0..|arr.length) {
    line = new StringBuffer()
    for (j in 0..|arr[i].length) {
      line.append(" ").append(arr[i][j])
    }
    if (line.toString() == line.toString().toUpperCase()) {
      line.append(" <-- [UPPERCASED]")
    }
    print(line)
  }
}

function printCommonArrayExceptions(arr: String[][]) {
  try {
    arr[100][100] = "hola"
  }
  catch (ex: Exception) {
    print("\nException: \n${ex.Class.Name}\n${ex.Message}")
  }
}

function printTitle(message: String) {
  print("")
  print("=".repeat(54))
  print(message)
  print("=".repeat(54))
}

class Alphabet {
  // Array Field
  var _letters: Character[]

  // Indexer Getter/Setter
  // cannot use property get because no parameter allowed for index
  // cannot use property set because only 1 parameter allowed (can use Map<int,char>)
  // property get getAt(index:int): Character { return letters[index] }
  // property set setAt(value: Map<int, Character>) { letters[value[0]] = value[1]
  function getAt(index: int): Character {
    return _letters[index]
  }
  function setAt(index: int, value: Character) {
    _letters[index] = String.valueOf(value).toUpperCase().charAt(0)
  }

  // Getter
  function getLength(): int {
    return _letters.length
  }

  // Constructors
  construct(size: int) {
    _letters = new Character[size]
  }

  construct(list: String) {
    _letters = list.toUpperCase().toCharArray().toList().toTypedArray()
  }

  construct(list: Character[]) {
    _letters = list
  }

  // Overridden Method
  override function toString(): String {
    return _letters.join(",")
  }

  // Method
  function slice(start: int, length: int): Character[] {
    return _letters.toList().subList(start, start+length).toTypedArray()
  }
}


The output:








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

Sunday, February 5, 2012

Factorial and Fibonacci in Gosu



Here below a little program in Gosu 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 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 Gosu
package com.series
uses com.series.Stopwatch
uses java.math.BigInteger
uses java.util.Scanner
uses java.lang.System

// static class
static class StaticFiborial {
  // Static Field
  private static var className: String = "Static Constructor"
  //  no available static constructor support
  // you can initialize your static fields instead
  /*static construct() {  // error: constructors cannot be static
    className = "Static Constructor";
    print(className)
  }*/
  // Static Method - Factorial Recursive
  static function factorialR( n : int ) : BigInteger {
    if (n == 1) {
      return BigInteger.ONE
    }
    else {
      return BigInteger.valueOf(n).multiply(factorialR(n - 1))
    }
  }
  // Class/Static Method - Factorial Imperative
  static function factorialI( n : int ) : BigInteger {
    var res = BigInteger.ONE
    while (n > 1) {
      res = res.multiply(BigInteger.valueOf(n))
      n -= 1
    }
    return res
  }
  // Static Method - Fibonacci Recursive
  static function fibonacciR( n : int ) : long {
    if (n < 2) {
      return 1
    }
    else {
      return fibonacciR(n - 1) + fibonacciR(n - 2)
    }
  }
  // Static Method - Fibonacci Imperative
  static function fibonacciI( n : int ) : long {
    var pre : long = 1
    var cur : long = 1
    var tmp : long = 0
    for ( i in 2..n ) {
      tmp = cur + pre
      pre = cur
      cur = tmp
    }
    return cur
  }
  // Static Method - Benchmarking Algorithms
  static function benchmarkAlgorithm( algorithm : int, values : List<int>) {
    var timer = new Stopwatch()
    var testValue = 0
    var facTimeResult : BigInteger = BigInteger.ZERO
    var fibTimeResult : long = 0
    // "Switch" Flow Control Statement
    switch (algorithm)
    {
      case 1:
          print("\nFactorial Imperative:")
          // "For" Loop Statement
          for (i in 0..values.size()-1) {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            facTimeResult = factorialI(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
          }
          break
      case 2:
          print("\nFactorial Recursive:")
          // "While" Loop Statement
          var i = 0
          while ( i < values.size() ) {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            facTimeResult = factorialR(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
            i++
          }
          break
      case 3:
          print("\nFibonacci Imperative:")
          // "Do-While" Loop Statement
          var i = 0
          do {
            testValue = values.get(i).intValue()
            // Taking Time
            timer.start()
            fibTimeResult = fibonacciI(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
            i++
          } while (i < values.size());
          break
      case 4:
          print("\nFibonacci Recursive:")
          // "For Each" Loop Statement
          for (item in values) {
            testValue = item
            // Taking Time
            timer.start()
            facTimeResult = fibonacciR(testValue)
            timer.stop()
            // Getting Time
            print(" (${testValue}) = ${timer.getElapsed()}")
          }
          break
    }
  }
}

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

// Console Program
print("Static 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. Calling method from instantiated object
var ff = new 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 (generic) list of values to test
//From 5 to 50 by 5
var values = new List<int>()
var i = 5
while (i < 55) {
  values.add(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
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()

And the Output is:























































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

static class Fiborial {
  // Using a StringBuffer as a list of string elements
  static function getFactorialSeries( n : int ) : String {
    // Create the String that will hold the list
    var 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
    for (i in n..0){
      // 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).toString())
    // return the list as a string
    return series.toString()
  }

  // Using a StringBuffer as a list of string elements
  static function getFibonnaciSeries( n : int ) : String {
    // Create the String that will hold the list
    var 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 (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()
  }

  static function factorial( n : int  ) : BigInteger {
    if (n == 1)
      return BigInteger.ONE
    else
      return BigInteger.valueOf(n).multiply(factorial(n - 1))
  }

  static function fibonacci( n : int ) : long {
    if (n < 2)
      return 1
    else
      return fibonacci(n - 1) + fibonacci(n - 2)
  }
}

// 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))

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/initializers, methods, etc.

// Fiborial.gs
package com.series

// Instance Class
class Fiborial {
  // Instance Field
  private var _instanceCount : int
  // Static Field - no static constructor so it needs to be initialized here
  private static var _staticCount : int = 0
  // Instance Read-Only Property
  // Within instance members, you can always use
  // the "this" reference pointer to access your (instance) members.
  property get InstanceCount() : int {
    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.
  static property get StaticCount() : int {
    return _staticCount
  }
  // Instance Constructor
  construct() {
    this._instanceCount = 0
    print("\nInstance Constructor ${this.instanceCount}")
  }
  // Static Constructor
  // not supported in Gosu. Constructor cannot be static.
  /*static construct() {
    staticCount = 0;
    print("\nStatic Constructor $staticCount")
  }
  */
  // Instance Method
  function factorial( n : int ) {
    this._instanceCount += 1
    print("\nFactorial(${n})")
  }
  // Static Method
  static function fibonacci( n : int ) {
    _staticCount += 1
    print("\nFibonacci(${n})")
  }
}
// FiborialExtrasApp.gsp
package com.series

// Calling Static Constructor and Methods
// No need to instantiate
Fiborial.fibonacci(5)

// Calling Instance Constructor and Methods
// Instance required
var fib = new Fiborial()
fib.factorial(5)

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

// Calling Instance Constructor and Methods
// for a second object
var fib2 = new Fiborial()
fib2.factorial(5)

print("")
// Calling Static Property
print("Static Count = ${Fiborial.getStaticCount()}")
// Calling Instance Property of object 1 and 2
print("Instance 1 Count = ${fib.getInstanceCount()}")
print("Instance 2 Count = ${fib2.getInstanceCount()}")

And the Output is:

























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


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

// Long Factorial
function factorialInt64( n : int ) : long
{
  if (n == 1)
    return 1
  else
    return n * factorialInt64(n - 1)
}

// Double Factorial
function factorialDouble( n : int ) : double
{
  if (n == 1)
    return 1
  else
    return n * factorialDouble(n - 1)
}

// BigInteger Factorial
function factorialBigInteger( n : int ) : BigInteger
{
  if (n == 1)
    return BigInteger.ONE
  else
    return BigInteger.valueOf(n).multiply(factorialBigInteger(n - 1))
}

var timer = new Stopwatch()
var facIntResult : long = 0
var facDblResult : double = 0
var facBigResult = BigInteger.ZERO

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

And the Output is:



Saturday, November 13, 2010

Gosu - Basics by Example



Extending my Basics by Example series to a new language :D. today's version of the post written in Gosu 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
// Gosu Basics
classpath "."
//package gsgreetprogram
uses java.util.Calendar
uses java.util.GregorianCalendar
uses java.util.Scanner
uses java.lang.System

public class Greet {
    // Fields or Attributes
    private var _message: String
    private var _name: String
    private var _loopMessage: int
    // Properties
    public property get Message(): String {
        return this._message
    }
    public property set Message(value: String) {
        this._message = this.capitalize(value)
    }
    public property get Name(): String {
        return this._name 
    }
    public property set Name(value: String) {
        this._name = this.capitalize(value)
    }
    public property get LoopMessage(): int {
        return this._loopMessage
    }
    public property set LoopMessage(value: int) {
        this._loopMessage = value
    }
    // Constructor
    public construct() {
        this._message = ""
        this._name = ""
        this._loopMessage = 0
    }
    // Overloaded Constructor
    public construct(pmessage: String, pname: String, ploopMessage: int) {
        this._message = pmessage
        this._name = pname
        this._loopMessage = ploopMessage
    }
    // Method 1
    private function capitalize(val: String): String {
        // "if-then-else" statement
        if(val.length >= 1) {
            return val.capitalize()
        }
        else {
            return ""
        }
    }
    // Method 2
    public function salute() {
        // "for" statement        
        for (i in 0..this._loopMessage) {
            print("${this._message} ${this._name}!")
        }
    }
    // Overloaded Method 2.1
    public function salute(pmessage: String, pname: String, ploopMessage: int) {
        // "while" statement
        var i: int = 0
        while (i < ploopMessage) {
            print("${this.capitalize(pmessage)} ${this.capitalize(pname)}!")
            i = i + 1
        }
    }
    // Overloaded Method 2.2    
 public function salute(pname: String) {    
  // "switch/case" statement    
  var dtNow = new GregorianCalendar()
  switch (dtNow.get(Calendar.HOUR_OF_DAY))
  {    
   case 6: case 7: case 8: case 9: case 10: case 11:    
    this._message = "good morning,"
    break
   case 12: case 13: case 14: case 15: case 16: case 17:    
    this._message = "good afternoon,"
    break
   case 18: case 19: case 20: case 21: case 22:    
    this._message = "good evening,"
    break
   case 23: case 0: case 1: case 2: case 3: case 4: case 5:    
    this._message = "good night,"
    break
   default:    
    this._message = "huh?"
  }    
  print("${this.capitalize(this._message)} ${this.capitalize(pname)}!")
 }    
}

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor        
var g = new Greet()
// Call Set Properties        
g.Message = "hello"            
g.Name = "world"            
g.LoopMessage = 5
// Call Method 2            
g.salute()        
// Call Method 2.1 and Get Properties            
g.salute(g.Message, "gosu", g.LoopMessage)        
// Call Method 2.2            
g.salute("carlos")            
// Stop and exit            
print("Press any key to exit...")
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()

Greetings Program - Minimal
// Gosu Basics
classpath "."
uses java.util.Calendar
uses java.util.GregorianCalendar
uses java.util.Scanner
uses java.lang.System

class Greet {
    // Fields or Attributes
    var _message: String
    var _name: String
    var _loopMessage: int
    // Properties
    property get Message(): String {
        return _message
    }
    property set Message(value: String) {
        _message = capitalize(value)
    }
    property get Name(): String {
        return _name 
    }
    property set Name(value: String) {
        _name = capitalize(value)
    }
    property get LoopMessage(): int {
        return _loopMessage
    }
    property set LoopMessage(value: int) {
        _loopMessage = value
    }
    // Constructor
    construct() {
        _message = ""
        _name = ""
        _loopMessage = 0
    }
    // Overloaded Constructor
    construct(pmessage: String, pname: String, ploopMessage: int) {
        _message = pmessage
        _name = pname
        _loopMessage = ploopMessage
    }
    // Method 1
    private function capitalize(val: String): String {
        // "if-then-else" statement
        if(val.length >= 1) {
            return val.capitalize()
        }
        else {
            return ""
        }
    }
    // Method 2
    function salute() {
        // "for" statement        
        for (i in 0.._loopMessage) {
            print("${_message} ${_name}!")
        }
    }
    // Overloaded Method 2.1
    function salute(pmessage: String, pname: String, ploopMessage: int) {
        // "while" statement
        var i = 0
        while (i < ploopMessage) {
            print("${capitalize(pmessage)} ${capitalize(pname)}!")
            i = i + 1
        }
    }
    // Overloaded Method 2.2    
    function salute(pname: String) {
        // "switch/case" statement    
        var dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))
        {    
            case 6: case 7: case 8: case 9: case 10: case 11:    
                _message = "good morning,"
                break
            case 12: case 13: case 14: case 15: case 16: case 17:
                _message = "good afternoon,"
                break
            case 18: case 19: case 20: case 21: case 22:    
                _message = "good evening,"
                break
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:    
                _message = "good night,"
                break    
            default:    
                _message = "huh?"
        }    
        print("${capitalize(_message)} ${capitalize(pname)}!")
    }    
}

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor        
var g = new Greet()
// Call Set Properties        
g.Message = "hello"            
g.Name = "world"            
g.LoopMessage = 5
// Call Method 2            
g.salute()        
// Call Method 2.1 and Get Properties            
g.salute(g.Message, "gosu", g.LoopMessage)        
// Call Method 2.2            
g.salute("carlos")            
// Stop and exit            
print("Press any key to exit...")
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()


And the Output is:




Auto-Implemented Properties in Gosu

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.

// Gosu Basics
class AutoImplementedProperties {
    // Fields + Auto-Implemented Properties
    var _message: String as Message
    var _name: String as Name
    var _loopMessage: int as LoopMessage
    // Methods
    function salute() {
        print("${_message.capitalize()} ${_name.capitalize()} ${_loopMessage}!")
    }
}

var g = new AutoImplementedProperties()
// Call Set Properties
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
// print them out
g.salute()
// and print them again using Get Properties
print(g.Message + " " + g.Name + " " + g.LoopMessage + "!")

And the output is:

Friday, November 12, 2010

OO Hello World - Gosu



The Hello World version of the program in Gosu!

A new OO programming language targeting the JVM with a Java-like syntax and compatible with java code. This looks like a promising language that deserves to be in the list of the ~20 languages I'm writing on here.

So, let's see how it looks like and how it compares to the other langs in a minimal OO program :D 


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: String
    construct(name: String) {
        _name = name.capitalize()  
    }
    function salute() {
        print("Hello ${_name}!")
    }
}

// Greet Program
var g = new Greet("world")
g.salute()

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

//classpath "."
//package greetprogram
uses java.util.*

public class Greet {
    private var _name: String
    public construct(name: String) {
        this._name = name.capitalize()  
    }
    public function salute() {
        print("Hello ${this._name}!")
    }
}

// Greet Program
var g = new Greet("world")
g.salute()

The Program Output:









Gosu Info:
“Gosu is an imperative statically-typed object-oriented programming language that is designed to be expressive, easy-to-read, and reasonably fast. Gosu supports several resource types” Taken from: (http://gosu-lang.org/intro.shtml)

Appeared:
2010
Current Version:
Developed by:
Guidewire Software
Creator:

Influenced by:
Java (James Gosling)
Predecessor Language

Predecessor Appeared

Predecessor Creator

Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.gsp”
Keywords:
53
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:

Latest IDE Support:
Eclipse
IntelliJ IDEA
Language Reference:
Extra Info: