Tweet
Happy Halloween to everybody!
What are the most horrifying Programming Languages you have came across or at least read on the Internet? Those languages that if someone come to you and ask you to Maintain or Extend a program written on them you will probably refuse or at least think twice before accepting?
Here below some of them, which I will certainly say "NO, thanks" straight away.
Malbolge
Malbolge is a public domain esoteric programming language invented by Ben Olmstead in 1998, named after the eighth circle of hell in Dante's Inferno, the Malebolge.
The peculiarity of Malbolge is that it was designed to be the most difficult and esoteric programming language. However, several of the tricks used to make understanding it difficult can be simplified away.
Malbolge was so difficult to understand when it arrived that it took two years for the first Malbolge program to appear. The program was not even written by a human being: it was generated by a beam search algorithm designed by Andrew Cooke and implemented in Lisp.
"Hello world" in Malbolge
(more on Malbolge in: http://en.wikipedia.org/wiki/Malbolge)
Whitespace
Whitespace is an esoteric programming language developed by Edwin Brady and Chris Morris at the University of Durham (also developers of the Kaya programming language). It was released on 1 April 2003 (April Fool's Day). Its name is a reference to whitespace characters. Unlike most programming languages, which ignore or assign little meaning to most whitespace characters, the Whitespace interpreter ignores any non-whitespace characters. Only spaces, tabs and linefeeds have meaning.[1] An interesting consequence of this property is that a Whitespace program can easily be contained within the whitespace characters of a program written in another language, making the text a polyglot.
The language itself is an imperative stack-based language. The virtual machine on which the programs run has a stack and a heap. The programmer is free to push arbitrary width integers onto the stack (currently there is no implementation of floating point numbers) and can also access the heap as a permanent store for variables and data structures.
"Hello world" in Whitespace
Pink = Space and Purple = Tab
(more on Whitespace in: http://en.wikipedia.org/wiki/Whitespace_(programming_language))
Brainfuck
The brainfuck programming language is an esoteric programming language noted for its extreme minimalism. It is a Turing tarpit, designed to challenge and amuse programmers, and is not suitable for practical use.[1] Its name has been variously bowdlerized. The name of the language is generally not capitalized except at the start of a sentence, although it is a proper noun.
Urban Müller created brainfuck in 1993 with the intention of designing a language which could be implemented with the smallest possible compiler,[2] inspired by the 1024-byte compiler for the FALSE programming language.[3] Several brainfuck compilers have been made smaller than 200 bytes. The classic distribution is Müller's version 2, containing a compiler for the Amiga, an interpreter, example programs, and a readme document.
The language consists of eight commands, listed below. A brainfuck program is a sequence of these commands, possibly interspersed with other characters (which are ignored). The commands are executed sequentially, except as noted below; an instruction pointer begins at the first command, and each command it points to is executed, after which it normally moves forward to the next command. The program terminates when the instruction pointer moves past the last command.
"Hello world" in Brainfuck
(more on Brainfuck in: http://en.wikipedia.org/wiki/Brainfuck)
Definitions and info of each programming language mentioned on this post as well as the hello world examples were taken from Wikipedia.org :)
If you want to know more about each of those languages and others you can find them here:
http://en.wikipedia.org/wiki/Category:Esoteric_programming_languages
What other languages do you think can be listed here?
I was thinking about Assembler, even if for some might be easy, but for those of us that started with structured or object oriented high level languages it looks little bit cryptic.
Sunday, October 31, 2010
JRuby - Basics by Example
Tweet
Continue with the Basics by Example; today's version of the post written in JRuby Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
Greetings Program - Minimal
And the Output is:
Where to define Class Fields/Attributes in JRuby
Auto-Implemented Properties in JRuby
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.
Overloading Constructor and Methods in JRuby
Ruby does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elseif code to handle both(or multiple) cases yourself.
And the Output is:
Continue with the Basics by Example; today's version of the post written in JRuby Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
# JRuby basics
require "java"
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System
module RbGreetProgram
class Greet
# Fields or Attributes
@message = ""
@name = ""
@loopMessage = 0
# Properties | Getters, Setters
def message
@message
end
def message=(val)
@message = capitalize(val)
end
def name
@name
end
def name=(val)
@name = capitalize(val)
end
def loopMessage
@loopMessage
end
def loopMessage=(val)
@loopMessage = val
end
# Constructor or Initializer Method
def initialize
@message = ""
@name = ""
@loopMessage = 0
end
# Overloaded Constructor
# No Overloaded Constructors/Initializers Support in Ruby
# Method 1
def capitalize(val)
# "if-then-else" statement
if val.length >= 1
return val.capitalize
else
return ""
end
end
private :capitalize
# Method 2
def salute
# "for" statement
for i in 0..@loopMessage
puts "#@message #@name!"
end
end
# Overloaded Method
# No Overloaded Methods Support in Ruby. New methods instead.
# Method 2.1
def salute21(message, name, loopMessage)
# "while" statement
i = 0
while i < loopMessage do
puts "#{capitalize(message)} #{capitalize(name)}!"
i += 1
end
end
# Method 2.2
def salute22(name)
# "switch/case" statement
dtNow = GregorianCalendar.new
@message = case dtNow.get(Calendar::HOUR_OF_DAY)
when 6..11 then "good morning,"
when 12..17 then "good afternoon,"
when 18..22 then "good evening,"
when 23,0..5 then "good night,"
else "huh?"
end
puts "#{capitalize(@message)} #{capitalize(name)}!"
end
end
# Console Program
# Define variable object of type Greet
# Instantiate Greet. Call Constructor
g = Greet.new
# Call Set Properties
g.message = "hello"
g.name = "world"
g.loopMessage = 5
# Call Method 2
g.salute()
# Call Method 2.1 and Get Properties
g.salute21(g.message, "jRuby", g.loopMessage)
# Call Method 2.2
g.salute22("carlos")
# Stop and exit
puts "Press any key to exit..."
gets
end
Greetings Program - Minimal
# JRuby basics
require "java"
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System
class Greet
# Fields or Attributes
@message = ""
@name = ""
@loopMessage = 0
# Properties | Getters, Setters
def message
@message
end
def message=(val)
@message = capitalize(val)
end
def name
@name
end
def name=(val)
@name = capitalize(val)
end
def loopMessage
@loopMessage
end
def loopMessage=(val)
@loopMessage = val
end
# Constructor or Initializer Method
def initialize
@message = ""
@name = ""
@loopMessage = 0
end
# Overloaded Constructor
# No Overloaded Constructors/Initializers Support in Ruby
# Method 1
def capitalize(val)
# "if-then-else" statement
if val.length >= 1
return val.capitalize
else
return ""
end
end
private :capitalize
# Method 2
def salute
# "for" statement
for i in 0..@loopMessage
puts "#@message #@name!"
end
end
# Overloaded Method
# No Overloaded Methods Support in Ruby. New methods instead.
# Method 2.1
def salute21(message, name, loopMessage)
# "while" statement
i = 0
while i < loopMessage do
puts "#{capitalize(message)} #{capitalize(name)}!"
i += 1
end
end
# Method 2.2
def salute22(name)
# "switch/case" statement
dtNow = GregorianCalendar.new
@message = case dtNow.get(Calendar::HOUR_OF_DAY)
when 6..11 then "good morning,"
when 12..17 then "good afternoon,"
when 18..22 then "good evening,"
when 23,0..5 then "good night,"
else "huh?"
end
puts "#{capitalize(@message)} #{capitalize(name)}!"
end
end
# Console Program
# Define variable object of type Greet
# Instantiate Greet. Call Constructor
g = Greet.new
# Call Set Properties
g.message = "hello"
g.name = "world"
g.loopMessage = 5
# Call Method 2
g.salute()
# Call Method 2.1 and Get Properties
g.salute21(g.message, "jRuby", g.loopMessage)
# Call Method 2.2
g.salute22("carlos")
# Stop and exit
puts "Press any key to exit..."
gets
And the Output is:
Where to define Class Fields/Attributes in JRuby
puts "Class Attributes Example:"
class ClassAttributes
# You do not need to explicitly add the Fields/Attributes as shown below within the class:
# message = ""
# name = ""
# loopMessage = 0
# because they are added to the class as Fields/Attributes the first time they appear in
# your code. For example, here below, in the Initialize method,
# we have 2 fields (name and message)
def initialize
@message = "message" # class field
@name = "name" # class field
end
# and one more within a public method (loopMessage)
def salute
@loopMessage = 1 # class field
localtest = 0 # local variable
puts "#@message, #@name, #@loopMessage"
end
end
# Then, you can access each of them as you normally do:
f = ClassAttributes.new
f.salute
Auto-Implemented Properties in JRuby
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.
puts ""
puts "Auto-Implemented Properties Example:"
# Ruby basics
class Greet
# Fields or Attributes
#@message = ""
# Manual Properties | Getters, Setters
#def message
# @message
#end
#def message=(val)
# @message = capitalize(val)
#end
# Instead of creating a field and a manual property (as above)
# we use the attributes syntax to create our Auto-Implemented Property
# that will be linked to our @message class field/attribute
attr_accessor :message
# you can also create read or write only props using attr_writer|attr_reader
def initialize
@message = ""
end
def salute
puts "#@message"
end
end
g = Greet.new
# we set the value of message through our write property
g.message = "hello ruby"
g.salute
# or get the value from it as well
puts g.message
Overloading Constructor and Methods in JRuby
Ruby does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elseif code to handle both(or multiple) cases yourself.
puts ""
puts "Overloaded-like Constructor and Method Example:"
class Overloading
# Constructor with variable arguments
def initialize(*args)
# if args list/sequence is not empty we use the arguments,
# otherwise we use the class fields
if args.size > 0
@message = args[0]
@name = args[1]
@loopMessage = args[2]
else
@message = 'empty_message'
@name = 'empty_name'
@loopMessage = 2
end
end
# Method with variable arguments
def salute(*args)
# if args list/sequence is not empty we use the arguments,
# otherwise we use the class fields
if args.size > 0
for i in 1..args[2]
puts "#{args[0]}, #{args[1]}!"
end
else
for i in 1..@loopMessage
puts "#@message, #@name!"
end
end
end
end
# and now we use the "overloaded-like" constructor and method
# calling constructor without parameters
o1 = Overloading.new
# calling method without parameters
o1.salute
# calling method with parameters
o1.salute("Hello", "JRuby", 3)
# calling constructor with with parameters
o2 = Overloading.new("Hello", "Carlos", 2)
# calling method without parameters
o2.salute
And the Output is:
Saturday, October 30, 2010
Jython - Basics by Example
Tweet
Continue with the Basics by Example; today's version of the post written in Jython Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
Greetings Program - Minimal
And the Output is:
Private Fields and Methods in Jython
"There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
Name mangling is intended to give classes an easy way to define 'private' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.)". Taken from: "http://docs.python.org/release/2.5.2/tut/node11.html#SECTION0011600000000000000000"
Where to define Class Fields/Attributes in Jython
Overloading Constructor and Methods in Jython
Python does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elif code to handle both(or multiple) cases yourself.
And the Output is:
Continue with the Basics by Example; today's version of the post written in Jython Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
# Jython Basics
import java
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
class Greet(object):
# Fields of Attributes
__message = ''
__name = ''
__loopMessage = 0
# Properties
def getMessage(self):
return self.__message
def setMessage(self, value):
self.__message = self.__capitalize(value)
Message = property(getMessage, setMessage)
def getName(self):
return self.__name
def setName(self, value):
self.__name = self.__capitalize(value)
Name = property(getName, setName)
def getLoopMessage(self):
return self.__loopMessage
def setLoopMessage(self, value):
self.__loopMessage = value
LoopMessage = property(getLoopMessage, setLoopMessage)
# Constructor or Initializer Method
def __init__(self):
self.__message = ''
self.__name = ''
self.__loopMessage = 0
# Overloaded Constructor
# No Overloaded Constructors Support in Python
# Method 1
def __capitalize(self, val):
# "if-then-else" statement
if len(val) >= 1:
return val.capitalize()
else:
return ""
# Method 2
def salute(self):
# "for" statement
for i in range(0, self.__loopMessage):
print self.__message, self.__name + '!'
# Overloaded Method
# No Overloaded Methods Support in Python. New methods instead.
# Method 2.1
def salute21(self, message, name, loopMessage):
# "while" statement
i = 0
while i < loopMessage:
print self.__capitalize(message), self.__capitalize(name) + '!'
i = i + 1
# Method 2.2
def salute22(self, name):
# "switch/case" statement is not supported
# so I'm using if then else if...
dtNow = GregorianCalendar()
hh = dtNow.get(Calendar.HOUR_OF_DAY)
if hh in range(6,12):
self.__message = "good morning,"
elif hh in range(12,18):
self.__message = "good evening,"
elif hh in range(18,23):
self.__message = "good afternoon,"
elif hh == 23 or hh in range(0,6):
self.__message = "good night,"
else:
self.__message = "huh?"
print self.__capitalize(self.__message), self.__capitalize(name) + '!'
# Console Program
def main():
# Define variable object of type Greet
# Instantiate Greet. Call Constructor
g = Greet()
# Call Set Properties
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
# Call Method 2
g.salute()
# Call Method 2.1 and Get Properties
g.salute21(g.Message, "jython", g.LoopMessage)
# Call Method 2.2
g.salute22("carlos")
# Stop and exit
print "Press any key to exit..."
sin = Scanner(System.in)
line = sin.nextLine()
sin.close()
main()
Greetings Program - Minimal
# Jython Basics
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
class Greet(object):
# Fields of Attributes
__message = ''
__name = ''
__loopMessage = 0
# Properties
def getMessage(self):
return self.__message
def setMessage(self, value):
self.__message = self.__capitalize(value)
Message = property(getMessage, setMessage)
def getName(self):
return self.__name
def setName(self, value):
self.__name = self.__capitalize(value)
Name = property(getName, setName)
def getLoopMessage(self):
return self.__loopMessage
def setLoopMessage(self, value):
self.__loopMessage = value
LoopMessage = property(getLoopMessage, setLoopMessage)
# Constructor or Initializer Method
def __init__(self):
self.__message = ''
self.__name = ''
self.__loopMessage = 0
# Overloaded Constructor
# No Overloaded Constructors Support in Python
# Method 1
def __capitalize(self, val):
# "if-then-else" statement
if len(val) >= 1:
return val.capitalize()
else:
return ""
# Method 2
def salute(self):
# "for" statement
for i in range(0, self.__loopMessage):
print self.__message, self.__name + '!'
# Overloaded Method
# No Overloaded Methods Support in Python. New methods instead.
# Method 2.1
def salute21(self, message, name, loopMessage):
# "while" statement
i = 0
while i < loopMessage:
print self.__capitalize(message), self.__capitalize(name) + '!'
i = i + 1
# Method 2.2
def salute22(self, name):
# "switch/case" statement is not supported
# so I'm using if then else if...
dtNow = GregorianCalendar()
hh = dtNow.get(Calendar.HOUR_OF_DAY)
if hh in range(6,12):
self.__message = "good morning,"
elif hh in range(12,18):
self.__message = "good evening,"
elif hh in range(18,23):
self.__message = "good afternoon,"
elif hh == 23 or hh in range(0,6):
self.__message = "good night,"
else:
self.__message = "huh?"
print self.__capitalize(self.__message), self.__capitalize(name) + '!'
# Console Program
# Define variable object of type Greet
# Instantiate Greet. Call Constructor
g = Greet()
# Call Set Properties
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
# Call Method 2
g.salute()
# Call Method 2.1 and Get Properties
g.salute21(g.Message, "jython", g.LoopMessage)
# Call Method 2.2
g.salute22("carlos")
# Stop and exit
print "Press any key to exit..."
sin = Scanner(System.in)
line = sin.nextLine()
sin.close()
And the Output is:
Private Fields and Methods in Jython
"There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.
Name mangling is intended to give classes an easy way to define 'private' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.)". Taken from: "http://docs.python.org/release/2.5.2/tut/node11.html#SECTION0011600000000000000000"
print 'Private Access Modifier Example:'
class Greet(object):
# Fields of Attributes
__message = ''
__name = ''
__loopMessage = 0
# Constructor or Initializer Method
def __init__(self):
self.__message = ''
self.__name = ''
self.__loopMessage = 0
# Private Method
def __capitalize(self, val):
if len(val) >= 1:
return val.capitalize()
else:
return ""
# Public Method
def Salute(self):
for i in range(0, self.__loopMessage):
print self.__message, self.__name + '!'
g = Greet()
# publicly accessing private fields (_classname__fieldname)
g._Greet__message = "hello"
g._Greet__name = "world"
g._Greet__loopMessage = 5
# Call Public Method
g.Salute()
# Call Private Method (_classname__methodname)
print g._Greet__capitalize('capitalized!')
Where to define Class Fields/Attributes in Jython
print ''
print 'Class Attributes Example:'
class ClassAttributes(object):
# You do not need to explicitly add the Fields/Attributes as shown below within the class:
# message = ''
# name = ''
# loopMessage = 0
# because they are added to the class as Fields/Attributes the first time they appear in
# your code. For example, here below, in the Initialize method,
# we have 2 fields (name and message)
def __init__(self):
self.message = '' # class field
self.name = '' # class field
# and one more within a public method (loopMessage)
def Salute(self):
self.loopMessage = 0 # class field
localtest = 0 # local variable
# Then, you can access each of them as you normally do:
f = ClassAttributes()
f.message = 'Hello'
f.name = 'World'
f.loopMessage = 5
print f.message, f.name, f.loopMessage
Overloading Constructor and Methods in Jython
Python does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elif code to handle both(or multiple) cases yourself.
print ''
print 'Overloaded-like Constructor and Method Example:'
class Overloading(object):
# Constructor with variable arguments
def __init__(self, *args):
# if args list/sequence is not empty we use the arguments,
# otherwise we use the class fields
if args:
self.message = args[0]
self.name = args[1]
self.loopMessage = args[2]
else:
self.message = 'empty_message'
self.name = 'empty_name'
self.loopMessage = 2
# Method with variable arguments
def Salute(self, *args):
# if args list/sequence is not empty we use the arguments,
# otherwise we use the class fields
if args:
for i in range(0, args[2]):
print args[0], args[1] + '!'
else:
for i in range(0, self.loopMessage):
print self.message, self.name + '!'
# and now we use the "overloaded-like" constructor and method
# calling constructor without parameters
o1 = Overloading()
# calling method without parameters
o1.Salute()
# calling method with parameters
o1.Salute('Hello', 'Jython', 3)
# calling constructor with with parameters
o2 = Overloading('Hello', 'Carlos', 2)
# calling method without parameters
o2.Salute()
And the Output is:
Fantom - Basics by Example
Tweet
Continue with the Basics by Example; today's version of the post written in Fantom Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
Greetings Program - Minimal
And the Output is:
Emulating Overloaded Constructor in Fantom
Fantom does not support Overloading Constructors by design, but you can some how "emulate" it by calling the constructor with an initializers list as shown here below.
And the Output is:
Continue with the Basics by Example; today's version of the post written in Fantom Enjoy!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.
There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html
Greetings Program - Verbose
// Fantom Basics
internal class Greet
{
// Fields or Attributes
private Str? message
private Str? name
private Int? loopMessage
// Properties, Getters and Setters
public Str Message
{
get { return this.&message }
set { this.&message = this.capitalize(it) }
}
public Str Name
{
get { return this.&name }
set { this.&name = this.capitalize(it) }
}
public Int LoopMessage
{
get { return this.&loopMessage }
set { this.&loopMessage = it }
}
// Constructor
public new make()
{
this.message = ""
this.name = ""
this.loopMessage = 0
}
// Overloaded Constructor
// No Overloaded Constructor support as designed
// Method 1
private Str capitalize(Str val)
{
// "if-then-else" statement
if (val.size() >= 1) {
return val.capitalize()
}
else {
return ""
}
}
// Method 2
public Void salute()
{
// "for" statement
for (i:=1; i<=this.loopMessage; i++)
{
echo("$this.message $this.name!")
}
}
// Overloaded Method
// No Overloaded Methods Support in Fantom. News methods instead.
// Method 2.1
public Void salute21(Str message, Str name, Int loopMessage)
{
// "while" statement
Int i := 0
while(i < loopMessage)
{
echo("${this.capitalize(message)} ${this.capitalize(name)}!")
i++
}
}
// Method 2.2
public Void salute22(Str name)
{
// "switch/case" statement
DateTime dtNow := DateTime.now();
switch(dtNow.hour)
{
case 6: case 7: case 8: case 9: case 10: case 11:
this.message = "good morning,"
case 12: case 13: case 14: case 15: case 16: case 17:
this.message = "good afternoon,"
case 18: case 19: case 20: case 21: case 22:
this.message = "good evening,"
case 23: case 0: case 1: case 2: case 3: case 4: case 5:
this.message = "good night,"
default:
this.message = "huh?"
}
echo("${this.capitalize(this.message)} ${this.capitalize(name)}!")
}
}
// Console Program
public class FanGreetProgram
{
public static Void main()
{
// Define variable object of type Greet and Instantiate. Call Constructor
Greet g := Greet.make()
// Call Setters
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
// Call Method 2
g.salute()
// Overloaded Method 2.1 and Getters
g.salute21(g.Message, "fantom", g.LoopMessage)
// Overloaded Method 2.2
g.salute22("carlos")
// Stop and exit
echo("Press any key to exit...")
console := Env.cur
userInput := console.in.readLine
}
}
Greetings Program - Minimal
// Fantom Basics
class Greet
{
// Fields or Attributes
private Str? message
private Str? name
private Int? loopMessage
// Properties, Getters and Setters
Str Message
{
get { return &message }
set { &message = capitalize(it) }
}
Str Name
{
get { return &name }
set { &name = capitalize(it) }
}
Int LoopMessage
{
get { return &loopMessage }
set { &loopMessage = it }
}
// Constructor
new make()
{
message = ""
name = ""
loopMessage = 0
}
// Overloaded Constructor
// No Overloaded Constructor support as designed
// Method 1
private Str capitalize(Str val)
{
// "if-then-else" statement
if (val.size >= 1) {
return val.capitalize
}
else {
return ""
}
}
// Method 2
Void salute()
{
// "for" statement
for (i:=1; i<=loopMessage; i++)
{
echo("$message $name!")
}
}
// Overloaded Method
// No Overloaded Methods Support in Fantom. News methods instead.
// Method 2.1
Void salute21(Str message, Str name, Int loopMessage)
{
// "while" statement
Int i := 0
while(i < loopMessage)
{
echo("${capitalize(message)} ${capitalize(name)}!")
i++
}
}
// Method 2.2
Void salute22(Str name)
{
// "switch/case" statement
DateTime dtNow := DateTime.now;
switch(dtNow.hour)
{
case 6: case 7: case 8: case 9: case 10: case 11:
message = "good morning,"
case 12: case 13: case 14: case 15: case 16: case 17:
message = "good afternoon,"
case 18: case 19: case 20: case 21: case 22:
message = "good evening,"
case 23: case 0: case 1: case 2: case 3: case 4: case 5:
message = "good night,"
default:
message = "huh?"
}
echo("${capitalize(message)} ${capitalize(name)}!")
}
}
// Console Program
class FanGreetProgram
{
static Void main()
{
// Define variable object of type Greet and Instantiate. Call Constructor
Greet g := Greet()
// Call Setters
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
// Call Method 2
g.salute
// Overloaded Method 2.1 and Getters
g.salute21(g.Message, "fantom", g.LoopMessage)
// Overloaded Method 2.2
g.salute22("carlos")
// Stop and exit
echo("Press any key to exit...")
console := Env.cur
userInput := console.in.readLine
}
}
And the Output is:
Emulating Overloaded Constructor in Fantom
Fantom does not support Overloading Constructors by design, but you can some how "emulate" it by calling the constructor with an initializers list as shown here below.
class Greet
{
// defining public fields
Str? message
Str? name
Int? loopMessage
// Constructor
new make()
{
echo("greet.make")
message = "empty_message"
name = "empty_name"
loopMessage = 0
}
// Method 2
Void Salute()
{
echo("$this.loopMessage $this.message $this.name!")
}
}
class Program
{
static Void main()
{
// calling constructor (printing greet.make)
Greet g := Greet()
g.Salute()
// calling constructor (printing greet.make) and explicitly assigning values to each field
// this can be done if the fields are defined as public
// or you will get a Private field xxx not accessible
Greet g2 := Greet{ message="hello"; name="world"; loopMessage=5 }
g2.Salute()
}
}
And the Output is:
Subscribe to:
Posts (Atom)







