langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,31 @@
class ClassExample
properties private -- class scope
foo = int
properties public -- publicly visible
bar = boolean
properties indirect -- generates bean patterns
baz = String()
method main(args=String[]) static -- main method
clsex = ClassExample() -- instantiate
clsex.foo = 42
clsex.baz = 'forty-two'
clsex.bar = 0 -- boolean false
clsex.test(clsex.foo)
clsex.test(clsex.bar)
clsex.test(clsex.baz)
method test(s=int)
aap = 1 -- local (stack) variable
say s aap
method test(s=String)
noot = 2
say s noot
method test(s=boolean)
mies = 3
say s mies

View file

@ -0,0 +1,5 @@
class my_class =
object (self)
val mutable variable = 0
method some_method = variable <- 1
end

View file

@ -0,0 +1,22 @@
MODULE M;
TYPE
T = POINTER TO TDesc;
TDesc = RECORD
x: INTEGER
END;
PROCEDURE New*(): T;
VAR t: T;
BEGIN
NEW(t); t.x := 0;
RETURN t
END New;
PROCEDURE (t: T) Increment*;
BEGIN
INC(t.x)
END Increment;
END M.

View file

@ -0,0 +1,33 @@
bundle Default {
class MyClass {
@var : Int;
New() {
}
method : public : SomeMethod() ~ Nil {
@var := 1;
}
method : public : SetVar(var : Int) ~ Nil {
@var := var;
}
method : public : GetVar() ~ Int {
return @var;
}
}
class Test {
function : Main(args : String[]) ~ Nil {
inst := MyClass->New();
inst->GetVar()->PrintLine();
inst->SomeMethod();
inst->GetVar()->PrintLine();
inst->SetVar(15);
inst->GetVar()->PrintLine();
}
}
}

View file

@ -0,0 +1,35 @@
type
MyClass = object
variable: integer;
constructor init;
destructor done;
procedure someMethod;
end;
constructor MyClass.init;
begin
variable := 0;
end;
procedure MyClass.someMethod;
begin
variable := 1;
end;
var
instance: MyClass; { as variable }
pInstance: ^MyClass; { on free store }
begin
{ create instances }
instance.init;
new(pInstance, init); { alternatively: pInstance := new(MyClass, init); }
{ call method }
instance.someMethod;
pInstance^.someMethod;
{ get rid of the objects }
instance.done;
dispose(pInstance, done);
end;

View file

@ -0,0 +1,11 @@
// There are no class variables, so static variables are used.
static int myClassVariable = 0;
@interface MyClass : NSObject
{
int variable; // instance variable
}
- (int)variable; // Typical accessor - you should use the same name as the variable
@end

View file

@ -0,0 +1,16 @@
@implementation MyClass
// Was not declared because init is defined in NSObject
- init
{
if (self = [super init])
variable = 0;
return self;
}
- (int)variable
{
return variable;
}
@end

View file

@ -0,0 +1,8 @@
// Creating an instance
MyClass *mc = [[MyClass alloc] init];
// Sending a message
[mc variable];
// Releasing it. When its reference count goes to zero, it will be deallocated
[mc release];

View file

@ -0,0 +1,74 @@
class SuperString
indexbase 1
union
bstring s
sys bs
sys *y
int *i
byte *b
float *f
end union
method space(sys n)
s=space n
end method
method delete()
freememory bs : bs=0
end method
method clear()
sys j, le=length
if le then
for j=1 to le : b[j]=0 : next
end if
end method
method length() as sys
if bs then return i[0]
end method
method resize(sys n)
sys le=length
if n<le
s=left s,n
elseif n>le
s+=nuls n-le
end if
end method
method fill(string f)
sys j, ls=length, lf=len f
for j=1 to ls step lf
mid s,j,f
next
end method
method constructor()
end method
method destructor
delete
end method
end class
'#recordof SuperString
'=====
'TESTS
'=====
new SuperString ss
'
ss.space 100
ss.resize 8
ss.fill "abc"
'
print ss.s 'result abcabcab
print ss.b[3] 'result 99: ascii for 'c'
'
del ss

View file

@ -0,0 +1,24 @@
declare
class Something
feat
name %% immutable, public attribute (called a "feature")
attr
count %% mutable, private attribute
%% public method which is used as an initializer
meth init(N)
self.name = N
count := 0
end
%% public method
meth increase
count := @count + 1
end
end
in
%% create an instance
Object = {New Something init("object")}
%% call a method
{Object increase}

View file

@ -0,0 +1,7 @@
class Camel { has Int $.humps = 1; }
my Camel $a .= new;
say $a.humps; # Automatically generated accessor method.
my Camel $b .= new: humps => 2;
say $b.humps;

View file

@ -0,0 +1,26 @@
class Butterfly {
has Int $!age; # The ! twigil makes it private.
has Str $.name;
has Str $.color;
has Bool $.wings;
submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {
# BUILD is called by bless. Its primary use is to to control
# object initialization.
$!wings = $!age > 1;
}
method flap() {
say ($.wings
?? 'Watch out for that hurricane!'
!! 'No wings to flap.');
}
}
my Butterfly $a .= new: age => 5;
say "Name: {$a.name}, Color: {$a.color}";
$a.flap;
my Butterfly $b .= new(name => 'Osgood', age => 4);
say "Name: {$b.name}, Color: {$b.color}";
$b.flap;

View file

@ -0,0 +1,4 @@
uses objectclass;
define :class MyClass;
slot value = 1;
enddefine;

View file

@ -0,0 +1,13 @@
;;; Construct instance with default slot values
lvars instance1 = newMyClass();
;;; Construct instance with explicitely given slot values
lvars instance2 = consMyClass(15);
;;; Print slot value using dot notation
instance1.value =>
instance2.value =>
;;; Print slot value using funtional notation
value(instance1) =>
;;; Change slot value
12 -> value(instance1);
;;; Print it
value(instance1) =>

View file

@ -0,0 +1,6 @@
define :method reset(x : MyClass);
0 -> value(x);
enddefine;
reset(instance1);
;;; Print it
instance1 =>

View file

@ -0,0 +1,56 @@
Interface OO_Interface ; Interface for any value of this type
Get.i()
Set(Value.i)
ToString.s()
Destroy()
EndInterface
Structure OO_Structure ; The *VTable structure
Get.i
Set.i
ToString.i
Destroy.i
EndStructure
Structure OO_Var
*VirtualTable.OO_Structure
Value.i
EndStructure
Procedure OO_Get(*Self.OO_Var)
ProcedureReturn *Self\Value
EndProcedure
Procedure OO_Set(*Self.OO_Var, n)
*Self\Value = n
EndProcedure
Procedure.s OO_ToString(*Self.OO_Var)
ProcedureReturn Str(*Self\Value)
EndProcedure
Procedure Create_OO()
*p.OO_Var=AllocateMemory(SizeOf(OO_Var))
If *p
*p\VirtualTable=?VTable
EndIf
ProcedureReturn *p
EndProcedure
Procedure OO_Destroy(*Self.OO_Var)
FreeMemory(*Self)
EndProcedure
DataSection
VTable:
Data.i @OO_Get()
Data.i @OO_Set()
Data.i @OO_ToString()
Data.i @OO_Destroy()
EndDataSection
;- Test the code
*Foo.OO_Interface = Create_OO()
*Foo\Set(341)
MessageRequester("Info", "Foo = " + *Foo\ToString() )
*Foo\Destroy()

View file

@ -0,0 +1,30 @@
Class Foo
Private Value.i
BeginPublic
Method Init()
; Any needed code goes here
EndMethod
Method Release()
; Any code befoe freeing the object goes here
EndMethod
Method Get()
MethodReturn This\Value
EndMethod
Method Set(n)
This\Value = n
EndMethod
Method.s ToString()
MethodReturn Str(This\Value)
EndMethod
EndPublic
EndClass
;- Test the code
*Demo.foo = NewObject.foo()
*Demo\Set(4)
MessageRequester("Info", "Val= " + *Demo\ToString())

View file

@ -0,0 +1,41 @@
rebol [
Title: "Classes"
Author: oofoe
Date: 2009-12-11
URL: http://rosettacode.org/wiki/Classes
]
; Objects are derived from the base 'object!' type. REBOL uses a
; prototyping object system, so any object can be treated as a class,
; from which to derive others.
cowboy: make object! [
name: "Tex" ; Instance variable.
hi: does [ ; Method.
print [self/name ": Howdy!"]]
]
; I create two instances of the 'cowboy' class.
tex: make cowboy []
roy: make cowboy [
name: "Roy" ; Override 'name' property.
]
print "Say 'hello', boys:" tex/hi roy/hi
print ""
; Now I'll subclass 'cowboy'. Subclassing looks a lot like instantiation:
legend: make cowboy [
deed: "..."
boast: does [
print [self/name ": I once" self/deed "!"]]
]
; Instancing the legend:
pecos: make legend [name: "Pecos Bill" deed: "lassoed a twister"]
print "Howdy, Pecos!" pecos/hi
print "Tell us about yourself?" pecos/boast

View file

@ -0,0 +1,17 @@
TYPE MyClass EXTENDS QObject
Variable AS INTEGER
CONSTRUCTOR
Variable = 0
END CONSTRUCTOR
SUB someMethod
MyClass.Variable = 1
END SUB
END TYPE
' create an instance
DIM instance AS MyClass
' invoke the method
instance.someMethod

View file

@ -0,0 +1,7 @@
class Alpha
'I am Alpha.' as greeting
define say_hello
greeting print
class Beta extend Alpha
'I am Beta!' as greeting

View file

@ -0,0 +1,2 @@
Alpha as alpha
Beta as beta

View file

@ -0,0 +1,2 @@
alpha.say_hello
beta.say_hello

View file

@ -0,0 +1,2 @@
I am Alpha.
I am Beta!

View file

@ -0,0 +1,12 @@
prototypes define: #MyPrototype &parents: {Cloneable} &slots: #(instanceVar).
MyPrototype traits addSlot: #classVar.
x@(MyPrototype traits) new
[
x clone `>> [instanceVar: 0. ]
].
x@(MyPrototype traits) someMethod
[
x instanceVar = 1 /\ (x classVar = 3)
].

View file

@ -0,0 +1,22 @@
MyClass {
classvar someVar, <another, <>thirdVar; // Class variables.
var <>something, <>somethingElse; // Instance variables.
// Note: variables are private by default. In the above, "<" enables getting, ">" enables setting
*new {
^super.new.init // constructor is a class method. typically calls some instance method to set up, here "init"
}
init {
something = thirdVar.squared;
somethingElse = this.class.name;
}
*aClassMethod {
^ someVar + thirdVar // The "^" means to return the result. If not specified, then the object itself will be returned ("^this")
}
anInstanceMethod {
something = something + 1;
}
}

View file

@ -0,0 +1,35 @@
class Car
{
//Constructor function.
function this(brand, weight, price = 0) {
this.brand = brand;
this.weight = weight || 1000; // Resort to default value (with 'or' notation).
this._price = price;
}
property price(v) // computable property, special kind of member function
{
get { return this._price; } // getter section
set { this._price = v; } // setter section
}
function toString() { // member function, method of a Car.
return String.printf("<%s>",this.brand);
}
}
class Truck : Car
{
function this(brand, size) {
super(brand, 2000); // Call of constructor of super class (Car here)
this.size = size; // Custom property for just this object.
}
}
var cars = [ // Some example car objects.
new Car("Mazda"),
new Truck("Volvo", 2, 30000)
];
for (var (i,car) in cars) // TIScript allows enumerate indexes and values
{
stdout.printf("#%d %s $%d %v %v, %v %v", i, car.brand, car.price, car.weight, car.size,
car instanceof Car, car instanceof Truck);
}

View file

@ -0,0 +1,31 @@
Private Const m_default = 10
Private m_bar As Integer
Private Sub Class_Initialize()
'constructor, can be used to set default values
m_bar = m_default
End Sub
Private Sub Class_Terminate()
'destructor, can be used to do some cleaning up
'here we just print a message
Debug.Print "---object destroyed---"
End Sub
Property Let Bar(value As Integer)
m_bar = value
End Property
Property Get Bar() As Integer
Bar = m_bar
End Property
Function DoubleBar()
m_bar = m_bar * 2
End Function
Function MultiplyBar(x As Integer)
'another method
MultiplyBar = m_bar * x
'Note: instead of using the instance variable m_bar we could refer to the Bar property of this object using the special word "Me":
' MultiplyBar = Me.Bar * x
End Function

View file

@ -0,0 +1,37 @@
Public Sub foodemo()
'declare and create separately
Dim f As Foo
Dim f0 As Foo
Set f = New Foo
'set property
f.Bar = 25
'call method
f.DoubleBar
'alternative
Call f.DoubleBar
Debug.Print "f.Bar is "; f.Bar
Debug.Print "Five times f.Bar is "; f.MultiplyBar(5)
'declare and create at the same time
Dim f2 As New Foo
Debug.Print "f2.Bar is "; f2.Bar 'prints default value
'destroy an object
Set f = Nothing
'create an object or not, depending on a random number:
If Rnd() < 0.5 Then
Set f0 = New Foo
End If
'check if object actually exists
If f0 Is Nothing Then
Debug.Print "object f0 does not exist"
Else
Debug.Print "object f0 was created"
End If
'at the end of execution all remaining objects created in this sub will be released.
'this will trigger one or two "object destroyed" messages
'depending on whether f0 was created...
End Sub

View file

@ -0,0 +1,29 @@
Class Foo
Private m_Bar As Integer
Public Sub New()
End Sub
Public Sub New(ByVal bar As Integer)
m_Bar = bar
End Sub
Public Property Bar() As Integer
Get
Return m_Bar
End Get
Set(ByVal value As Integer)
m_Bar = value
End Set
End Property
Public Sub DoubleBar()
m_Bar *= 2
End Sub
Public Function MultiplyBar(ByVal x As Integer) As Integer
Return x * Bar
End Function
End Class

View file

@ -0,0 +1,22 @@
'Declare and create separately
Dim foo1 As Foo
foo1 = New Foo
'Declare and create at the same time
Dim foo2 As New Foo
'... while passing constructor parameters
Dim foo3 As New Foo(5)
'... and them immediately set properties
Dim foo4 As New Foo With {.Bar = 10}
'Calling a method that returns a value
Console.WriteLine(foo4.MultiplyBar(20))
'Calling a method that performs an action
foo4.DoubleBar()
'Reading/writing properties
Console.WriteLine(foo4.Bar)
foo4.Bar = 1000