Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,7 @@
---
category:
- Object oriented
- Type System
- Encyclopedia
from: http://rosettacode.org/wiki/Classes
note: Basic language learning

33
Task/Classes/00-TASK.txt Normal file
View file

@ -0,0 +1,33 @@
In [[object-oriented programming]] '''class''' is a set (a [[wp:Transitive_closure|transitive closure]]) of types bound by the relation of [[inheritance]]. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the '''root type''' of the class.
A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called '''methods''' of the root type.
Both operations and values are called [[polymorphism | polymorphic]].
A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.
The action of choice the type-specific implementation of a polymorphic operation is called '''dispatch'''. Correspondingly, polymorphic operations are often called '''dispatching''' or '''virtual'''.
Operations with multiple arguments and/or the results of the class are called '''multi-methods'''.
A further generalization of is the operation with arguments and/or results from different classes.
* single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation ''x''.''f''() is used instead of mathematical ''f''(''x'').
* multiple-dispatch languages allow many arguments and/or results to control the dispatch.
<br>
A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called '''the most specific type''' of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.
In many [[object-oriented programming | OO]] languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in [[Ada]]).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.
;Task:
Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
<br><br>

View file

@ -0,0 +1,10 @@
T MyType
Int public_variable // member variable = instance variable
. Int private_variable
F () // constructor
.private_variable = 0
F someMethod() // member function = method
.private_variable = 1
.public_variable = 10

View file

@ -0,0 +1,3 @@
T MyType
F.virtual.new someMethod() -> N // this is polymorphic
print()

View file

@ -0,0 +1,82 @@
MODE MYDATA = STRUCT(
INT name1
);
STRUCT(
INT name2,
PROC (REF MYDATA)REF MYDATA new,
PROC (REF MYDATA)VOID init,
PROC (REF MYDATA)VOID some method
) class my data;
class my data := (
# name2 := # 2, # Class attribute #
# PROC new := # (REF MYDATA new)REF MYDATA:(
(init OF class my data)(new);
new
),
# PROC init := # (REF MYDATA self)VOID:(
""" Constructor (Technically an initializer rather than a true 'constructor') """;
name1 OF self := 0 # Instance attribute #
),
# PROC some method := # (REF MYDATA self)VOID:(
""" Method """;
name1 OF self := 1;
name2 OF class my data := 3
)
);
# class name, invoked as a function is the constructor syntax #
REF MYDATA my data = (new OF class my data)(LOC MYDATA);
MODE GENDEROPT = UNION(STRING, VOID);
MODE AGEOPT = UNION(INT, VOID);
MODE MYOTHERDATA = STRUCT(
STRING name,
GENDEROPT gender,
AGEOPT age
);
STRUCT (
INT count,
PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)REF MYOTHERDATA new,
PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)VOID init,
PROC (REF MYOTHERDATA)VOID del
) class my other data;
class my other data := (
# count := # 0, # Population of "(init OF class my other data)" objects #
# PROC new := # (REF MYOTHERDATA new, STRING name, GENDEROPT gender, AGEOPT age)REF MYOTHERDATA:(
(init OF class my other data)(new, name, gender, age);
new
),
# PROC init := # (REF MYOTHERDATA self, STRING name, GENDEROPT gender, AGEOPT age)VOID:(
""" One initializer required, others are optional (with different defaults) """;
count OF class my other data +:= 1;
name OF self := name;
gender OF self := gender;
CASE gender OF self IN
(VOID):gender OF self := "Male"
ESAC;
age OF self := age
),
# PROC del := # (REF MYOTHERDATA self)VOID:(
count OF class my other data -:= 1
)
);
PROC attribute error := STRING: error char; # mend the error with the "error char" #
# Allocate the instance from HEAP #
REF MYOTHERDATA person1 = (new OF class my other data)(HEAP MYOTHERDATA, "John", EMPTY, EMPTY);
print (((name OF person1), ": ",
(gender OF person1|(STRING gender):gender|attribute error), " ")); # "John Male" #
print (((age OF person1|(INT age):age|attribute error), new line)); # Raises AttributeError exception! #
# Allocate the instance from LOC (stack) #
REF MYOTHERDATA person2 = (new OF class my other data)(LOC MYOTHERDATA, "Jane", "Female", 23);
print (((name OF person2), ": ",
(gender OF person2|(STRING gender):gender|attribute error), " "));
print (((age OF person2|(INT age):age|attribute error), new line)) # "Jane Female 23" #

View file

@ -0,0 +1,21 @@
package {
public class MyClass {
private var myVariable:int; // Note: instance variables are usually "private"
/**
* The constructor
*/
public function MyClass() {
// creates a new instance
}
/**
* A method
*/
public function someMethod():void {
this.myVariable = 1; // Note: "this." is optional
// myVariable = 1; works also
}
}
}

View file

@ -0,0 +1,9 @@
package My_Package is
type My_Type is tagged private;
procedure Some_Procedure(Item : out My_Type);
function Set(Value : in Integer) return My_Type;
private
type My_Type is tagged record
Variable : Integer := -12;
end record;
end My_Package;

View file

@ -0,0 +1,13 @@
package body My_Package is
procedure Some_Procedure(Item : out My_Type) is
begin
Item := 2 * Item;
end Some_Procedure;
function Set(Value : Integer) return My_Type is
Temp : My_Type;
begin
Temp.Variable := Value;
return Temp;
end Set;
end My_Package;

View file

@ -0,0 +1,8 @@
with My_Package; use My_Package;
procedure Main is
Foo : My_Type; -- Foo is created and initialized to -12
begin
Some_Procedure(Foo); -- Foo is doubled
Foo := Set(2007); -- Foo.Variable is set to 2007
end Main;

View file

@ -0,0 +1,7 @@
class Circle (radius, x, y) extends Shape (x, y) implements Drawable {
var myvec = new Vector (x, y)
public function draw() {
// draw the circle
}
}

View file

@ -0,0 +1,27 @@
OBJECT a_class
varA, varP
ENDOBJECT
-> this could be used like a constructor
PROC init() OF a_class
self.varP := 10
self.varA := 2
ENDPROC
-> the special proc end() is for destructor
PROC end() OF a_class
-> nothing to do here...
ENDPROC
-> a not so useful getter
PROC getP() OF a_class IS self.varP
PROC main()
DEF obj : PTR TO a_class
NEW obj.init()
WriteF('\d\n', obj.varA) -> this can be done, while
-> varP can't be accessed directly
WriteF('\d\n', obj.varP) -> or
WriteF('\d\n', obj.getP())
END obj
ENDPROC

View file

@ -0,0 +1,53 @@
; defining a custom type
define :person [ ; define a new custom type "Person"
name ; with fields: name, surname, age
surname
age
][
; with custom post-construction initializer
init: [
this\name: capitalize this\name
]
; custom print function
print: [
render "NAME: |this\name|, SURNAME: |this\surname|, AGE: |this\age|"
]
; custom comparison operator
compare: 'age
]
; create a method for our custom type
sayHello: function [this][
ensure -> is? :person this
print ["Hello" this\name]
]
; create new objects of our custom type
a: to :person ["John" "Doe" 34] ; let's create 2 "Person"s
b: to :person ["jane" "Doe" 33] ; and another one
; call pseudo-inner method
sayHello a ; Hello John
sayHello b ; Hello Jane
; access object fields
print ["The first person's name is:" a\name] ; The first person's name is: John
print ["The second person's name is:" b\name] ; The second person's name is: Jane
; changing object fields
a\name: "Bob"
sayHello a ; Hello Bob
; verifying object type
print type a ; :person
print is? :person a ; true
; printing objects
print a ; NAME: John, SURNAME: Doe, AGE: 34
; sorting user objects (using custom comparator)
sort @[a b] ; Jane..., John...
sort.descending @[a b] ; John..., Jane...

View file

@ -0,0 +1,19 @@
obj := new MyClass
obj.WhenCreated()
class MyClass {
; Instance Variable #1
time := A_Hour ":" A_Min ":" A_Sec
; Constructor
__New() {
MsgBox, % "Constructing new object of type: " this.__Class
FormatTime, date, , MM/dd/yyyy
; Instance Variable #2
this.date := date
}
; Method
WhenCreated() {
MsgBox, % "Object created at " this.time " on " this.date
}
}

View file

@ -0,0 +1,18 @@
INSTALL @lib$+"CLASSLIB"
REM Declare the class:
DIM MyClass{variable, @constructor, _method}
DEF MyClass.@constructor MyClass.variable = PI : ENDPROC
DEF MyClass._method = MyClass.variable ^ 2
REM Register the class:
PROC_class(MyClass{})
REM Instantiate the class:
PROC_new(myclass{}, MyClass{})
REM Call the method:
PRINT FN(myclass._method)
REM Discard the instance:
PROC_discard(myclass{})

View file

@ -0,0 +1,13 @@
ExClass {
𝕊 value: # Constructor portion
priv value
priv2 0
ChangePriv { priv 𝕩 }
DispPriv {𝕊: •Show privpriv2 }
}
obj ExClass 5
obj.DispPriv@
obj.ChangePriv 6
obj.DispPriv@

View file

@ -0,0 +1,34 @@
PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"

View file

@ -0,0 +1,34 @@
PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books*
'--- the correct syntax for class
Book1 = new Books()
'--- initialize the strings const char* in c++
Book1->title = "C++ Programming to bacon "
Book1->author = "anyone"
Book1->subject ="RECORD Tutorial"
Book1->book_id = 1234567
PRINT "Book title : " ,Book1->title FORMAT "%s%s\n"
PRINT "Book author : ", Book1->author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1->subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1->book_id FORMAT "%s%d\n"

View file

@ -0,0 +1,16 @@
# Constructors can take parameters (that automatically become properties)
constructor Ball(color, radius)
# Objects can also have functions (closures)
:volume
return 4/3 * {pi} * (radius ** 3)
end
:show
return "a " + color + " ball with radius " + radius
end
end
red_ball = Ball("red", 2)
print(red_ball)
# => a red ball with radius 2

View file

@ -0,0 +1,8 @@
( ( resolution
= (x=)
(y=)
(new=.!arg:(?(its.x),?(its.y)))
)
& new$(resolution,640,480):?VGA
& new$(resolution,1920,1080):?1080p
& out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));

View file

@ -0,0 +1,29 @@
class MyClass
{
public:
void someMethod(); // member function = method
MyClass(); // constructor
private:
int variable; // member variable = instance variable
};
// implementation of constructor
MyClass::MyClass():
variable(0)
{
// here could be more code
}
// implementation of member function
void MyClass::someMethod()
{
variable = 1; // alternatively: this->variable = 1
}
// Create an instance as variable
MyClass instance;
// Create an instance on free store
MyClass* pInstance = new MyClass;
// Instances allocated with new must be explicitly destroyed when not needed any more:
delete pInstance;

View file

@ -0,0 +1,8 @@
class MyClass
{
public:
MyClass(): variable(0) {}
void someMethod() { variable = 1; }
private:
int variable;
};

View file

@ -0,0 +1,6 @@
class MyClass
{
public:
virtual void someMethod(); // this is polymorphic
virtual ~MyClass(); // destructor
};

View file

@ -0,0 +1,26 @@
public class MyClass
{
public MyClass()
{
}
public void SomeMethod()
{
}
private int _variable;
public int Variable
{
get { return _variable; }
set { _variable = value; }
}
public static void Main()
{
// instantiate it
MyClass instance = new MyClass();
// invoke the method
instance.SomeMethod();
// set the variable
instance.Variable = 99;
// get the variable
System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
}
}

31
Task/Classes/C/classes.c Normal file
View file

@ -0,0 +1,31 @@
#include <stdlib.h>
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc(sizeof *pthis);
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if (pthis)
{
free(*pthis);
*pthis = NULL;
}
}
void MyClass_someMethod(MyClass pthis)
{
pthis->variable = 1;
}
MyClass obj = MyClass_new();
MyClass_someMethod(obj);
MyClass_delete(&obj);

View file

@ -0,0 +1,66 @@
IDENTIFICATION DIVISION.
CLASS-ID. my-class INHERITS base.
*> The 'INHERITS base' and the following ENVIRONMENT DIVISION
*> are optional (in Visual COBOL).
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
CLASS base.
*> There is no way (as far as I can tell) of creating a
*> constructor. However, you could wrap it with another
*> method to achieve the desired effect.
*>...
OBJECT.
*> Instance data
DATA DIVISION.
WORKING-STORAGE SECTION.
01 instance-variable PIC 9(8).
*> Properties can have getters and setters automatically
*> generated.
01 a-property PIC 9(8) PROPERTY.
PROCEDURE DIVISION.
METHOD-ID. some-method.
PROCEDURE DIVISION.
*> ...
END METHOD some-method.
END OBJECT.
END CLASS my-class.
IDENTIFICATION DIVISION.
PROGRAM-ID. example-class-use.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
*> These declarations brings the class and property into
*> scope.
CLASS my-class
PROPERTY a-property.
DATA DIVISION.
WORKING-STORAGE SECTION.
*> Declaring a my-class reference variable.
01 instance USAGE OBJECT REFERENCE my-class.
PROCEDURE DIVISION.
*> Invoking a static method or (in this case) a constructor.
INVOKE my-class "new" RETURNING instance
*> Invoking an instance method.
INVOKE instance "some-method"
*> Using the setter and getter of a-property.
MOVE 5 TO a-property OF instance
DISPLAY a-property OF instance
GOBACK
.
END PROGRAM example-class-use.

View file

@ -0,0 +1,9 @@
; You can think of this as an interface
(defprotocol Foo (getFoo [this]))
; Generates Example1 Class with foo as field, with method that returns foo.
(defrecord Example1 [foo] Foo (getFoo [this] foo))
; Create instance and invoke our method to return field value
(-> (Example1. "Hi") .getFoo)
"Hi"

View file

@ -0,0 +1,15 @@
class Rectangle
# The constructor is defined as a bare function. This
# constructor accepts one argument and automatically assigns it
# to an instance variable.
(@width) ->
# Another instance variable.
length: 10
# A method.
area: ->
@width * @length
# Instantiate the class using the 'new' operator.
rect = new Rectangle 2

View file

@ -0,0 +1,14 @@
# Create a basic class
class Rectangle
# Constructor that accepts one argument
constructor: (@width) ->
# An instance variable
length: 10
# A method
area: () ->
@width * @length
# Instantiate the class using the new operator
rect = new Rectangle 2

View file

@ -0,0 +1,12 @@
(defclass circle ()
((radius :initarg :radius
:initform 1.0
:type number
:reader radius)))
(defmethod area ((shape circle))
(* pi (expt (radius shape) 2)))
> (defvar *c* (make-instance 'circle :radius 2))
> (area *c*)
12.566370614359172d0

View file

@ -0,0 +1,41 @@
MODULE Point;
IMPORT
Strings;
TYPE
Instance* = POINTER TO LIMITED RECORD
x-, y- : LONGINT; (* Instance variables *)
END;
PROCEDURE (self: Instance) Initialize*(x,y: LONGINT), NEW;
BEGIN
self.x := x;
self.y := y
END Initialize;
(* constructor *)
PROCEDURE New*(x, y: LONGINT): Instance;
VAR
point: Instance;
BEGIN
NEW(point);
point.Initialize(x,y);
RETURN point
END New;
(* methods *)
PROCEDURE (self: Instance) Add*(other: Instance): Instance, NEW;
BEGIN
RETURN New(self.x + other.x,self.y + other.y);
END Add;
PROCEDURE (self: Instance) ToString*(): POINTER TO ARRAY OF CHAR, NEW;
VAR
xStr,yStr: ARRAY 64 OF CHAR;
str: POINTER TO ARRAY OF CHAR;
BEGIN
Strings.IntToString(self.x,xStr);
Strings.IntToString(self.y,yStr);
NEW(str,128);str^ := "@(" +xStr$ + "," + yStr$ + ")";
RETURN str
END ToString;
END Point.

View file

@ -0,0 +1,17 @@
MODULE DrivePoint;
IMPORT
Point,
StdLog;
PROCEDURE Do*;
VAR
p,q: Point.Instance;
BEGIN
p := Point.New(1,2);
q := Point.New(2,1);
StdLog.String(p.ToString() + " + " + q.ToString() + " = " + p.Add(q).ToString());StdLog.Ln;
StdLog.String("p.x:> ");StdLog.Int(p.x);StdLog.Ln;
StdLog.String("p.y:> ");StdLog.Int(p.y);StdLog.Ln
END Do;
END DrivePoint.

View file

@ -0,0 +1,13 @@
class MyClass
def initialize
@instance_var = 0
end
def add_1
@instance_var += 1
end
end
my_class = MyClass.new

43
Task/Classes/D/classes.d Normal file
View file

@ -0,0 +1,43 @@
import std.stdio;
class MyClass {
//constructor (not necessary if empty)
this() {}
void someMethod() {
variable = 1;
}
// getter method
@property int variable() const {
return variable_;
}
// setter method
@property int variable(int newVariable) {
return variable_ = newVariable;
}
private int variable_;
}
void main() {
// On default class instances are allocated on the heap
// The GC will manage their lifetime
auto obj = new MyClass();
// prints 'variable = 0', ints are initialized to 0 by default
writeln("variable = ", obj.variable);
// invoke the method
obj.someMethod();
// prints 'variable = 1'
writeln("variable = ", obj.variable);
// set the variable using setter method
obj.variable = 99;
// prints 'variable = 99'
writeln("variable = ", obj.variable);
}

View file

@ -0,0 +1 @@
s

View file

@ -0,0 +1,22 @@
// Declare the class "/foo"
foo
// Everything inside the indented block is relative to the parent, "/foo" here.
// Instance variable "bar", with a default value of 0
// Here, var/bar is relative to /foo, thus it becomes "/foo/var/bar" ultimately.
var/bar = 0
// The "New" proc is the constructor.
New()
// Constructor code.
// Declares a proc called "Baz" on /foo
proc/baz()
// Do things.
// Instantiation code.
// Overriding /client/New() means it is ran when a client connects.
/client/New()
..()
var/foo/x = new /foo()
x.bar = 10 // Assign to the instance variable.
x.baz() // Call "baz" on our instance.

View file

@ -0,0 +1,25 @@
type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
begin
FSomeField := -1;
end;
procedure SomeMethod;
property SomeField: Integer read FSomeField write FSomeField;
end;
procedure TMyClass.SomeMethod;
begin
// do something
end;
var lMyClass: TMyClass;
lMyClass := new TMyClass; // can also use TMyClass.Create
lMyClass.SomeField := 99;
lMyClass.SomeMethod;

View file

@ -0,0 +1,44 @@
program SampleClass;
{$APPTYPE CONSOLE}
type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
destructor Destroy; override;
procedure SomeMethod;
property SomeField: Integer read FSomeField write FSomeField;
end;
constructor TMyClass.Create;
begin
FSomeField := -1
end;
destructor TMyClass.Destroy;
begin
// free resources, etc
inherited Destroy;
end;
procedure TMyClass.SomeMethod;
begin
// do something
end;
var
lMyClass: TMyClass;
begin
lMyClass := TMyClass.Create;
try
lMyClass.SomeField := 99;
lMyClass.SomeMethod();
finally
lMyClass.Free;
end;
end.

View file

@ -0,0 +1,5 @@
class run{
func val(){
showln 10+20
}
}

View file

@ -0,0 +1,8 @@
def makeColor(name :String) {
def color {
to colorize(thing :String) {
return `$name $thing`
}
}
return color
}

View file

@ -0,0 +1,5 @@
? def red := makeColor("red")
# value: <color>
? red.colorize("apple")
# value: "red apple"

View file

@ -0,0 +1,30 @@
type Bear ^| the type system is informed about the new type,
| here we are in the static context
|^
model # instance context
text name # instance variable
^|
| in EMal the instance variables are ordered, and a default
| variadic constructor is provided by the runtime.
| Every value passed to the constructor sets the instance variable
| according to the order.
|^
fun makeNoise = void by block # method of Bear
writeLine("Growl!")
end
end
type Cat
model
text noise
new by text noise # an explicit constructor
me.noise = noise # we must use me to access instance variables
end
fun makeNoise = void by block
writeLine(me.noise)
end
end
type Main
Bear bear = Bear("Bruno") # creating a new instance
writeLine("The bear is called " + bear.name)
bear.makeNoise()
Cat("Meow").makeNoise()

View file

@ -0,0 +1,30 @@
PROGRAM CLASS2_DEMO
CLASS QUADRATO
LOCAL LATO
PROCEDURE GETLATO(L)
LATO=L
END PROCEDURE
PROCEDURE AREA(->A)
A=LATO*LATO
END PROCEDURE
PROCEDURE PERIMETRO(->P)
P=4*LATO
END PROCEDURE
END CLASS
NEW P:QUADRATO,Q:QUADRATO
BEGIN
P_GETLATO(10)
P_AREA(->AREAP)
PRINT(AREAP)
Q_GETLATO(20)
Q_PERIMETRO(->PERIMETROQ)
PRINT(PERIMETROQ)
END PROGRAM

View file

@ -0,0 +1,11 @@
(lib 'gloops) ; load oo library
(define-class Person null (name (age :initform 66)))
(define-method tostring (Person) (lambda (p) ( format "🚶 %a " p.name)))
(define-method mailto (Person Person) (lambda( p o) (printf "From %a to %a : ..." p o)))
;; define a sub-class of Person with same methods
(define-class Writer (Person) (books))
(define-method tostring (Writer) (lambda (w)( format "🎩 %a" w.name)))
(define-method mailto (Person Writer)
(lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age w.books )))

View file

@ -0,0 +1,16 @@
;; instantiate
(define simone (make-instance Person :name 'simone :age 42)) ;; slots values by name
(define antoinette (make-instance Person :name 'antoinette :age 37))
(define albert (Person "albert" 33)) ;; quick way : slots values in order
(define simon (make-instance Writer :name "simon" :books '(my-life my-bike)))
(mailto simone simon) ;; method Person-Writer
(mailto simone antoinette) ;; method Person-Person
(mailto simon albert) ;; no method Writer-Person : call 'super' Person-Person
(mailto simon simon) ;; no mehod Writer-Writer : call 'super' Person-Writer
From 🚶 simone (age 42). Dear writer of (my-life my-bike) ...
From 🚶 simone to 🚶 antoinette : ...
From 🎩 simon to 🚶 albert : ...
From 🎩 simon (age 66). Dear writer of (my-life my-bike) ...

View file

@ -0,0 +1,2 @@
class MY_CLASS
end

View file

@ -0,0 +1,14 @@
class MY_CLASS
create
make
feature {NONE} -- Initialization
make
-- This is a creation procedure or "Constructor".
do
create my_string.make_empty
end
end

View file

@ -0,0 +1,43 @@
class MY_CLASS
create -- Here we are declaring ...
make, -- In the Feature group (below) we are coding
make_this_way, -- each of these declared creation procedures.
make_that_way, -- We can have as many constructors as we need.
make_another_way,
a_name_other_than_make
feature {NONE} -- Initialization
make
-- This is a creation procedure or "Constructor".
do
-- Initialization code goes here ...
end
make_this_way
-- Make this way, rather than a plain ole "make".
do
-- Initialization code goes here ...
end
make_that_way
-- Create that way rather than this way (above).
do
-- Initialization code goes here ...
end
make_another_way
-- And still another way to create MY_CLASS.
do
-- Initialization code goes here ...
end
a_name_other_than_make
-- There is no requirement to use the word "make".
-- The word "make" is just a naming convention.
do
-- Initialization code goes here ...
end
end

View file

@ -0,0 +1,48 @@
class MY_CLASS
create
make
feature {NONE} -- Initialization
make
-- This is a creation procedure or "Constructor".
do
create my_string.make_empty
end
feature -- Access (Properties)
my_string: STRING
-- This is a comment about `my_string', which is a "Property".
my_integer: INTEGER
-- Unlike `my_string' (above), the INTEGER type is an "Expanded Type".
-- This means INTEGER objects know how to self-initialize.
my_date: DATE
-- This attribute (or "Property") will need to be initialized.
-- One way to do that is to make a self-initializing attribute, thus ...
attribute
create Result.make_now
end
feature -- Basic Operations (Methods)
do_something
-- Loop over and print the numbers 1 to 100 to the console.
do
across 1 |..| 100 as i loop print (i.out) end
end
do_something_else
-- Set a and b and print the result.
local
a, b, c: INTEGER
do
a := 1
b := 2
c := a + b
end
end

View file

@ -0,0 +1,27 @@
import extensions;
class MyClass
{
prop int Variable;
someMethod()
{
Variable := 1
}
constructor()
{
}
}
public program()
{
// instantiate the class
var instance := new MyClass();
// invoke the method
instance.someMethod();
// get the variable
console.printLine("Variable=",instance.Variable)
}

View file

@ -0,0 +1,9 @@
type MyClass(init) = // constructor with one argument: init
let mutable var = init // a private instance variable
member x.Method() = // a simple method
var <- var + 1
printfn "%d" var
// create an instance and use it
let myObject = new MyClass(42)
myObject.Method()

View file

@ -0,0 +1,15 @@
open System
type Shape =
abstract Perimeter: unit -> float
abstract Area: unit -> float
type Circle(radius) =
interface Shape with
member x.Perimeter() = 2.0 * radius * Math.PI
member x.Area() = Math.PI * radius**2.0
type Rectangle(width, height) =
interface Shape with
member x.Perimeter() = 2.0 * width + 2.0 * height
member x.Area() = width * height

View file

@ -0,0 +1,8 @@
TUPLE: my-class foo bar baz ;
M: my-class quux foo>> 20 + ;
C: <my-class> my-class
10 20 30 <my-class> quux ! result: 30
TUPLE: my-child-class < my-class quxx ;
C: <my-child-class> my-child-class
M: my-child-class foobar 20 >>quux ;
20 20 30 <my-child-class> foobar quux ! result: 30

View file

@ -0,0 +1,6 @@
class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ]
[ static block ]
[ properties declaration ]
[init block]
[method list]
end

View file

@ -0,0 +1,15 @@
class mailbox( max_msg )
capacity = max_msg * 10
name = nil
messages = []
init
printl( "Box now ready for ", self.capacity, " messages." )
end
function slot_left()
return self.capacity - len( self.messages )
end
end

View file

@ -0,0 +1,2 @@
m = mailbox( 10 )
// Ouputs: Box now ready for 100 messages.

View file

@ -0,0 +1,26 @@
class MyClass {
read_slot: 'instance_var # creates getter method for @instance_var
@@class_var = []
def initialize {
# 'initialize' is the constructor method invoked during 'MyClass.new' by convention
@instance_var = 0
}
def some_method {
@instance_var = 1
@another_instance_var = "foo"
}
# define class methods: define a singleton method on the class object
def self class_method {
# ...
}
# you can also name the class object itself
def MyClass class_method {
# ...
}
}
myclass = MyClass new

View file

@ -0,0 +1,27 @@
class MyClass
{
// an instance variable
Int x
// a constructor, providing default value for instance variable
new make (Int x := 1)
{
this.x = x
}
// a method, return double the number x
public Int double ()
{
return 2 * x
}
}
class Main
{
public static Void main ()
{
a := MyClass (2) // instantiates the class, with x = 2
b := MyClass() // instantiates the class, x defaults to 1
c := MyClass { x = 3 } // instantiates the class, sets x to 3
}
}

View file

@ -0,0 +1,14 @@
:class MyClass <super Object
int memvar
:m ClassInit: ( -- )
ClassInit: super
1 to memvar ;m
:m ~: ( -- ) ." Final " show: [ Self ] ;m
:m set: ( n -- ) to memvar ;m
:m show: ( -- ) ." Memvar = " memvar . ;m
;class

View file

@ -0,0 +1 @@
MyClass newInstance

View file

@ -0,0 +1 @@
New> MyClass value newInstance

View file

@ -0,0 +1,2 @@
10 set: newInstance
show: newInstance

View file

@ -0,0 +1,2 @@
newInstance dispose
0 to newInstance \ no dangling pointers!

View file

@ -0,0 +1,5 @@
: test { \ obj -- }
New> MyClass to obj
show: obj
1000 set: obj
obj dispose ;

View file

@ -0,0 +1,31 @@
include FMS-SI.f
:class foo \ begin class foo definition
ivar x \ declare an instance variable named x
:m put ( n -- ) x ! ;m \ a method/message definition
:m init: 10 self put ;m \ the constructor method
:m print x ? ;m \ a print method for x
;class \ end class foo definition
foo f1 \ instantiate a foo object, in the dictionary, named f1
f1 print \ 10 send the print message to object f1
20 f1 put \ send a message with one parameter to the object
f1 print \ 20
: bar \ bar is a normal Forth function definition
heap> foo \ instantiate a nameless object in the heap
dup print
30 over put
dup print
<free ; \ destroy the heap object
: bar' \ bar' is an alternative to bar that uses a local variable
heap> foo {: f :}
f print
30 f put
f print
f <free ;
bar \ 10 30
bar' \ 10 30

View file

@ -0,0 +1,178 @@
!-----------------------------------------------------------------------
!Module accuracy defines precision and some constants
!-----------------------------------------------------------------------
module accuracy_module
implicit none
integer, parameter, public :: rdp = kind(1.d0)
! constants
real(rdp), parameter :: pi=3.141592653589793238462643383279502884197_rdp
end module accuracy_module
!-----------------------------------------------------------------------
!Module typedefs_module contains abstract derived type and extended type definitions.
! Note that a reserved word "class" in Fortran is used to describe
! some polymorphic variable whose data type may vary at run time.
!-----------------------------------------------------------------------
module typedefs_module
use accuracy_module
implicit none
private ! all
public :: TPoint, TShape, TCircle, TRectangle, TSquare ! public only these defined derived types
! abstract derived type
type, abstract :: TShape
real(rdp) :: area
character(len=:),allocatable :: name
contains
! deferred method i.e. abstract method = must be overridden in extended type
procedure(calculate_area), deferred,pass :: calculate_area
end type TShape
! just declaration of the abstract method/procedure for TShape type
abstract interface
function calculate_area(this)
use accuracy_module
import TShape !imports TShape type from host scoping unit and makes it accessible here
implicit none
class(TShape) :: this
real(rdp) :: calculate_area
end function calculate_area
end interface
! auxiliary derived type
type TPoint
real(rdp) :: x,y
end type TPoint
! extended derived type
type, extends(TShape) :: TCircle
real(rdp) :: radius
real(rdp), private :: diameter
type(TPoint) :: centre
contains
procedure, pass :: calculate_area => calculate_circle_area
procedure, pass :: get_circle_diameter
final :: finalize_circle
end type TCircle
! extended derived type
type, extends(TShape) :: TRectangle
type(TPoint) :: A,B,C,D
contains
procedure, pass :: calculate_area => calculate_rectangle_area
final :: finalize_rectangle
end type TRectangle
! extended derived type
type, extends(TRectangle) :: TSquare
contains
procedure, pass :: calculate_area => calculate_square_area
final :: finalize_square
end type TSquare
contains
! finalization subroutines for each type
! They called recursively, i.e. finalize_rectangle
! will be called after finalize_square subroutine
subroutine finalize_circle(x)
type(TCircle), intent(inout) :: x
write(*,*) "Deleting TCircle object"
end subroutine finalize_circle
subroutine finalize_rectangle(x)
type(TRectangle), intent(inout) :: x
write(*,*) "Deleting also TRectangle object"
end subroutine finalize_rectangle
subroutine finalize_square(x)
type(TSquare), intent(inout) :: x
write(*,*) "Deleting TSquare object"
end subroutine finalize_square
function calculate_circle_area(this)
implicit none
class(TCircle) :: this
real(rdp) :: calculate_circle_area
this%area = pi * this%radius**2
calculate_circle_area = this%area
end function calculate_circle_area
function calculate_rectangle_area(this)
implicit none
class(TRectangle) :: this
real(rdp) :: calculate_rectangle_area
! here could be more code
this%area = 1
calculate_rectangle_area = this%area
end function calculate_rectangle_area
function calculate_square_area(this)
implicit none
class(TSquare) :: this
real(rdp) :: calculate_square_area
! here could be more code
this%area = 1
calculate_square_area = this%area
end function calculate_square_area
function get_circle_diameter(this)
implicit none
class(TCircle) :: this
real(rdp) :: get_circle_diameter
this % diameter = 2.0_rdp * this % radius
get_circle_diameter = this % diameter
end function get_circle_diameter
end module typedefs_module
!-----------------------------------------------------------------------
!Main program
!-----------------------------------------------------------------------
program rosetta_class
use accuracy_module
use typedefs_module
implicit none
! we need this subroutine in order to show the finalization
call test_types()
contains
subroutine test_types()
implicit none
! declare object of type TPoint
type(TPoint), target :: point
! declare object of type TCircle
type(TCircle),target :: circle
! declare object of type TSquare
type(TSquare),target :: square
! declare pointers
class(TPoint), pointer :: ppo
class(TCircle), pointer :: pci
class(TSquare), pointer :: psq
!constructor
point = TPoint(5.d0,5.d0)
ppo => point
write(*,*) "x=",point%x,"y=",point%y
pci => circle
pci % radius = 1
write(*,*) pci % radius
! write(*,*) pci % diameter !No,it is a PRIVATE component
write(*,*) pci % get_circle_diameter()
write(*,*) pci % calculate_area()
write(*,*) pci % area
psq => square
write(*,*) psq % area
write(*,*) psq % calculate_area()
write(*,*) psq % area
end subroutine test_types
end program rosetta_class

View file

@ -0,0 +1,27 @@
' FB 1.05.0 Win64
Type MyClass
Private:
myInt_ As Integer
Public:
Declare Constructor(myInt_ As Integer)
Declare Property MyInt() As Integer
Declare Function Treble() As Integer
End Type
Constructor MyClass(myInt_ As Integer)
This.myInt_ = myInt_
End Constructor
Property MyClass.MyInt() As Integer
Return myInt_
End Property
Function MyClass.Treble() As Integer
Return 3 * myInt_
End Function
Dim mc As MyClass = MyClass(24)
Print mc.MyInt, mc.Treble()
Print "Press any key to quit the program"
Sleep

View file

@ -0,0 +1,19 @@
struct Rectangle{
float width;
float height;
};
Rectangle new(float width,float height){
Rectangle self;
self.width = width;
self.height = height;
return self;
}
float area(Rectangle self){
return self.width*self.height;
}
float perimeter(Rectangle self){
return (self.width+self.height)*2.0;
}

View file

@ -0,0 +1,50 @@
package main
import "fmt"
// a basic "class."
// In quotes because Go does not use that term or have that exact concept.
// Go simply has types that can have methods.
type picnicBasket struct {
nServings int // "instance variables"
corkscrew bool
}
// a method (yes, Go uses the word method!)
func (b *picnicBasket) happy() bool {
return b.nServings > 1 && b.corkscrew
}
// a "constructor."
// Also in quotes as Go does not have that exact mechanism as part of the
// language. A common idiom however, is a function with the name new<Type>,
// that returns a new object of the type, fully initialized as needed and
// ready to use. It makes sense to use this kind of constructor function when
// non-trivial initialization is needed. In cases where the concise syntax
// shown is sufficient however, it is not idiomatic to define the function.
// Rather, code that needs a new object would simply contain &picnicBasket{...
func newPicnicBasket(nPeople int) *picnicBasket {
// arbitrary code to interpret arguments, check resources, etc.
// ...
// return data new object.
// this is the concise syntax. there are other ways of doing it.
return &picnicBasket{nPeople, nPeople > 0}
}
// how to instantiate it.
func main() {
var pb picnicBasket // create on stack (probably)
pbl := picnicBasket{} // equivalent to above
pbp := &picnicBasket{} // create on heap. pbp is pointer to object.
pbn := new(picnicBasket) // equivalent to above
forTwo := newPicnicBasket(2) // using constructor
// equivalent to above. field names, called keys, are optional.
forToo := &picnicBasket{nServings: 2, corkscrew: true}
fmt.Println(pb.nServings, pb.corkscrew)
fmt.Println(pbl.nServings, pbl.corkscrew)
fmt.Println(pbp)
fmt.Println(pbn)
fmt.Println(forTwo)
fmt.Println(forToo)
}

View file

@ -0,0 +1,26 @@
import reflect
type happinessTester interface {
happy() bool
}
type bottleOfWine struct {
USD float64
empty bool
}
func (b *bottleOfWine) happy() bool {
return b.USD > 10 && !b.empty
}
func main() {
partySupplies := []happinessTester{
&picnicBasket{2, true},
&bottleOfWine{USD: 6},
}
for _, ps := range partySupplies {
fmt.Printf("%s: happy? %t\n",
reflect.Indirect(reflect.ValueOf(ps)).Type().Name(),
ps.happy())
}
}

View file

@ -0,0 +1,15 @@
/** Ye olde classe declaration */
class Stuff {
/** Heare bee anne instance variable declared */
def guts
/** This constructor converts bits into Stuff */
Stuff(injectedGuts) {
guts = injectedGuts
}
/** Brethren and sistren, let us flangulate with this fine flangulating method */
def flangulate() {
println "This stuff is flangulating its guts: ${guts}"
}
}

View file

@ -0,0 +1,16 @@
def stuff = new Stuff('''
I have made mistakes in the past.
I have made mistakes in the future.
-- Vice President Dan Quayle
''')
stuff.flangulate()
stuff.guts = '''
Our enemies are innovative and resourceful, and so are we.
They never stop thinking about new ways to harm our country and our people,
and neither do we.
-- President George W. Bush
'''
stuff.flangulate()

View file

@ -0,0 +1,33 @@
class Shape a where
perimeter :: a -> Double
area :: a -> Double
{- A type class Shape. Types belonging to Shape must support two
methods, perimeter and area. -}
data Rectangle = Rectangle Double Double
{- A new type with a single constructor. In the case of data types
which have only one constructor, we conventionally give the
constructor the same name as the type, though this isn't mandatory. -}
data Circle = Circle Double
instance Shape Rectangle where
perimeter (Rectangle width height) = 2 * width + 2 * height
area (Rectangle width height) = width * height
{- We made Rectangle an instance of the Shape class by
implementing perimeter, area :: Rectangle -> Int. -}
instance Shape Circle where
perimeter (Circle radius) = 2 * pi * radius
area (Circle radius) = pi * radius^2
apRatio :: Shape a => a -> Double
{- A simple polymorphic function. -}
apRatio shape = area shape / perimeter shape
main = do
print $ apRatio $ Circle 5
print $ apRatio $ Rectangle 5 5
{- The correct version of apRatio (and hence the correct
implementations of perimeter and area) is chosen based on the type
of the argument. -}

View file

@ -0,0 +1,23 @@
data Shape = Rectangle Double Double | Circle Double
{- This Shape is a type rather than a type class. Rectangle and
Circle are its constructors. -}
perimeter :: Shape -> Double
{- An ordinary function, not a method. -}
perimeter (Rectangle width height) = 2 * width + 2 * height
perimeter (Circle radius) = 2 * pi * radius
area :: Shape -> Double
area (Rectangle width height) = width * height
area (Circle radius) = pi * radius^2
apRatio :: Shape -> Double
{- Technically, this version of apRatio is monomorphic. -}
apRatio shape = area shape / perimeter shape
main = do
print $ apRatio $ Circle 5
print $ apRatio $ Rectangle 5 5
{- The value returned by apRatio is determined by the return values
of area and perimeter, which just happen to be defined differently
for Rectangles and Circles. -}

View file

@ -0,0 +1,21 @@
class Example (x) # 'x' is a field in class
# method definition
method double ()
return 2 * x
end
# 'initially' block is called on instance construction
initially (x)
if /x # if x is null (not given), then set field to 0
then self.x := 0
else self.x := x
end
procedure main ()
x1 := Example () # new instance with default value of x
x2 := Example (2) # new instance with given value of x
write (x1.x)
write (x2.x)
write (x2.double ()) # call a method
end

View file

@ -0,0 +1,11 @@
coclass 'exampleClass'
exampleMethod=: monad define
1+exampleInstanceVariable
)
create=: monad define
'this is the constructor'
)
exampleInstanceVariable=: 0

View file

@ -0,0 +1 @@
exampleObject=: conew 'exampleClass'

View file

@ -0,0 +1,19 @@
public class MyClass{
// instance variable
private int variable; // Note: instance variables are usually "private"
/**
* The constructor
*/
public MyClass(){
// creates a new instance
}
/**
* A method
*/
public void someMethod(){
this.variable = 1;
}
}

View file

@ -0,0 +1 @@
new MyClass();

View file

@ -0,0 +1,24 @@
//Constructor function.
function Car(brand, weight) {
this.brand = brand;
this.weight = weight || 1000; // Resort to default value (with 'or' notation).
}
Car.prototype.getPrice = function() { // Method of Car.
return this.price;
}
function Truck(brand, size) {
this.car = Car;
this.car(brand, 2000); // Call another function, modifying the "this" object (e.g. "superconstructor".)
this.size = size; // Custom property for just this object.
}
Truck.prototype = Car.prototype; // Also "import" the prototype from Car.
var cars = [ // Some example car objects.
new Car("Mazda"),
new Truck("Volvo", 2)
];
for (var i=0; i<cars.length; i++) {
alert(cars[i].brand + " " + cars[i].weight + " " + cars[i].size + ", " +
(cars[i] instanceof Car) + " " + (cars[i] instanceof Truck));
}

View file

@ -0,0 +1,77 @@
class Car {
/**
* A few brands of cars
* @type {string[]}
*/
static brands = ['Mazda', 'Volvo'];
/**
* Weight of car
* @type {number}
*/
weight = 1000;
/**
* Brand of car
* @type {string}
*/
brand;
/**
* Price of car
* @type {number}
*/
price;
/**
* @param {string} brand - car brand
* @param {number} weight - mass of car
*/
constructor(brand, weight) {
if (brand) this.brand = brand;
if (weight) this.weight = weight
}
/**
* Drive
* @param distance - distance to drive
*/
drive(distance = 10) {
console.log(`A ${this.brand} ${this.constructor.name} drove ${distance}cm`);
}
/**
* Formatted stats string
*/
get formattedStats() {
let out =
`Type: ${this.constructor.name.toLowerCase()}`
+ `\nBrand: ${this.brand}`
+ `\nWeight: ${this.weight}`;
if (this.size) out += `\nSize: ${this.size}`;
return out
}
}
class Truck extends Car {
/**
* Size of truck
* @type {number}
*/
size;
/**
* @param {string} brand - car brand
* @param {number} size - size of car
*/
constructor(brand, size) {
super(brand, 2000);
if (size) this.size = size;
}
}
let myTruck = new Truck('Volvo', 2);
console.log(myTruck.formattedStats);
myTruck.drive(40);

View file

@ -0,0 +1,20 @@
abstract type Mammal end
habitat(::Mammal) = "planet Earth"
struct Whale <: Mammal
mass::Float64
habitat::String
end
Base.show(io::IO, ::Whale) = print(io, "a whale")
habitat(w::Whale) = w.habitat
struct Wolf <: Mammal
mass::Float64
end
Base.show(io::IO, ::Wolf) = print(io, "a wolf")
arr = [Whale(1000, "ocean"), Wolf(50)]
println("Type of $arr is ", typeof(arr))
for a in arr
println("Habitat of $a: ", habitat(a))
end

View file

@ -0,0 +1,8 @@
class MyClass(val myInt: Int) {
fun treble(): Int = myInt * 3
}
fun main(args: Array<String>) {
val mc = MyClass(24)
print("${mc.myInt}, ${mc.treble()}")
}

View file

@ -0,0 +1,31 @@
(defmodule simple-object
(export all))
(defun fish-class (species)
"
This is the constructor used internally, once the children and fish id are
known.
"
(let ((habitat '"water"))
(lambda (method-name)
(case method-name
('habitat
(lambda (self) habitat))
('species
(lambda (self) species))))))
(defun get-method (object method-name)
"
This is a generic function, used to call into the given object (class
instance).
"
(funcall object method-name))
; define object methods
(defun get-habitat (object)
"Get a variable set in the class."
(funcall (get-method object 'habitat) object))
(defun get-species (object)
"Get a variable passed when constructing the object."
(funcall (get-method object 'species) object))

View file

@ -0,0 +1,8 @@
> (slurp '"simple-object.lfe")
#(ok simple-object)
> (set my-fish (fish-class '"Carp"))
#Fun<lfe_eval.10.91765564>
> (get-habitat my-fish)
"water"
> (get-species my-fish)
"Carp"

View file

@ -0,0 +1,19 @@
define mytype => type {
data
public id::integer = 0,
public val::string = '',
public rand::integer = 0
public onCreate() => {
// "onCreate" runs when instance created, populates .rand
.rand = math_random(50,1)
}
public asString() => {
return 'has a value of: "'+.val+'" and a rand number of "'+.rand+'"'
}
}
local(x = mytype)
#x->val = '99 Bottles of beer'
#x->asString // outputs 'has a value of: "99 Bottles of beer" and a rand number of "48"'

View file

@ -0,0 +1,19 @@
----------------------------------------
-- @desc Class "MyClass"
-- @file parent script "MyClass"
----------------------------------------
-- instance variable
property _myvar
-- constructor
on new (me)
me._myvar = 23
return me
end
-- a method
on doubleAndPrint (me)
me._myvar = me._myvar * 2
put me._myvar
end

View file

@ -0,0 +1,3 @@
foo = script("MyClass").new()
foo.doubleAndPrint()
-- 46

View file

@ -0,0 +1,24 @@
Section Header
+ name := SAMPLE;
Section Inherit
- parent : OBJECT := OBJECT;
Section Private
+ variable : INTEGER <- 0;
Section Public
- some_method <- (
variable := 1;
);
- main <- (
+ sample : SAMPLE;
sample := SAMPLE.clone;
sample.some_method;
);

View file

@ -0,0 +1,20 @@
:- object(metaclass,
instantiates(metaclass)).
:- public(new/2).
new(Instance, Value) :-
self(Class),
create_object(Instance, [instantiates(Class)], [], [state(Value)]).
:- end_object.
:- object(class,
instantiates(metaclass)).
:- public(method/1).
method(Value) :-
::state(Value).
:- private(state/1).
:- end_object.

View file

@ -0,0 +1,7 @@
| ?- class::new(Instance, 1).
Instance = o1
yes
| ?- o1::method(Value).
Value = 1
yes

View file

@ -0,0 +1,14 @@
myclass = setmetatable({
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
}, {
__call = function(z,n) return setmetatable({var = n}, myclass) end
})
instance = myclass(3)
print(instance.var) -->3
instance:setvar(6)
print(instance.var) -->6

View file

@ -0,0 +1,202 @@
Class zz {
module bb {
Superclass A {
unique:
counter
}
Superclass B1 {
unique:
counter
}
Superclass B2 {
unique:
counter
}
\\ We can make a group Alfa with a member, another group Beta
\\ Group Beta can't see parent group, but can see own member groups
\\ Group Alfa can see everything in nested groups, in any level,
\\ but can't see inside modules/functions/operator/value/set
Group Alfa {
Group Beta { }
}
Alfa=A
Alfa.Beta=B1
\\ we make 3 groups for marshaling counters
\\ each group get a superclass
Marshal1=A
Marshal2=B1
Marshal3=B2
\\ Now we want to add functionality7
\\ Inc module to add 1 to counter
\\ a Value function to return counter
\\ Without Value a group return a copy
\\ If a group has a value then we can get copy using Group(nameofgroup)
\\ just delete Group Marshal1 and remove Rem when we make Marshal1 using a class function
Group Marshal1 {
Module Inc {
For SuperClass {.counter++}
}
Value {
For SuperClass {=.counter}
}
}
Class AnyMarshal {
Module Inc {
For SuperClass {.counter++}
}
Value {
For SuperClass {=.counter}
}
}
\\ here we merge groups
Rem : Marshal1=AnyMarshal()
Marshal2=AnyMarshal()
Marshal3=AnyMarshal()
\\ So now we see counters (three zero)
Print Marshal1, Marshal2, Marshal3 \\ 0, 0, 0
\\ Now we prepare Alfa and Alfa.Beta groups
Group Alfa {
Group Beta {
Function SuperClass.Counter {
For SuperClass {
=.counter
}
}
}
Module PrintData {
For SuperClass {
Print .counter, This.Beta.SuperClass.Counter()
}
}
}
\\ some marshaling to counters
Marshal1.inc
Marshal2.inc
Marshal2.inc
Marshal3.inc
\\ lets print results
Print Marshal1, Marshal2, Marshal3 \\ 1 2 1
\\ Calling Alfa.PrintData
Alfa.PrintData \\ 1 2
\\ Merging a group in a group make a change to superclass pointer inside group
Alfa.Beta=B2 \\ change supeclass
Alfa.PrintData \\ 1 1
For i=1 to 10 : Marshal3.inc : Next i
Alfa.PrintData \\ 1 11
Alfa.Beta=B1 \\ change supeclass
Alfa.PrintData \\ 1 2
Epsilon=Alfa
Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1 -1
Epsilon.PrintData \\ 1 2
Alfa.Beta=B2 \\ change supeclass
Alfa.PrintData \\ 1 11
Epsilon.PrintData \\ 1 2
\\ validation being for top group superclass and all members if are same
\\ but not for inner superclasses. This maybe change in later revisions of language.
Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1 0
}
}
Dim A(10)
A(3)=zz()
A(3).bb
Report {
there is no super like java super in M2000 when we use inheritance through classes
see Superclass (example SUP) which is something differnent
}
class Shape {
private:
super.X, super.Y
Function super.toString$(a=10) {
="Shape(" + str$(.super.X,"") + ", " + str$(.super.Y,"") + ")"
}
public:
Module final setPosition (px, py) {
.super.X <= px
.super.Y <= py
}
Function toString$() {
=.super.toString$()
}
}
class MoveShape {
Module MoveRelative(xr, yr) {
.super.X+=xr
.super.Y+=yr
}
}
class Circle as MoveShape as Shape {
private:
radius
public:
Module setRadius (r) {
.radius <= r
}
Function toString$() {
= .super.toString$() + ": Circle(" + str$(.radius,"") + ")"
}
}
class Rectangle as MoveShape as Shape {
private:
height, width
public:
Module MoveLeftSide (p as *Rectangle) {
\\ for same type objects private members are like public
for This, p {
.super.X<=..super.X+..width
.super.Y<=..super.Y
}
}
module setDimensions (h,w) {
.height <= h
.width <= w
}
Function toString$() {
= .super.toString$() + ": Rectangle(" + str$(.height,"") + " x " + str$(.width,"") + ")"
}
}
c =Circle()
r = Rectangle()
r.setPosition 1, 2
r.setDimensions 50, 50
c.setPosition 3, 4
c.setRadius 10
Print r.tostring$()
Print c.tostring$()
r.MoveRelative 100,100
c.MoveRelative -50,-50
Print r.tostring$()
Print c.tostring$()
Report {
wokring with pointers like in c++
pointers in M2000 are objects, so null pointer (pc->0&) isn't a zero, but an empty Group (object)
}
pc->circle()
pr->rectangle()
pr=>setPosition 1, 2
pr=>setDimensions 50, 50
pc=>setPosition 3, 4
pc=>setRadius 10
Print pr=>tostring$()
Print pc=>tostring$()
\\ we can open up to ten objects (from one to ten dots, normaly one to three)
\\ if we use nestef for object {} also we have up to ten objects in total
\\ every for object {} is an area for temporary definitions, after exit from brackets
\\ any new definition erased.
For pr, pc {
.MoveRelative 100,100
..MoveRelative -50,-50
Print .tostring$()
Print ..tostring$()
}
pr2->rectangle()
pr2=>SetDimensions 30, 30
pr2=>MoveLeftSide pr
Print pr2=>toString$()

View file

@ -0,0 +1,12 @@
function GenericClassInstance = GenericClass(varargin)
if isempty(varargin) %No input arguments
GenericClassInstance.classVariable = 0; %Generates a struct
else
GenericClassInstance.classVariable = varargin{1}; %Generates a struct
end
%Converts the struct to a class of type GenericClass
GenericClassInstance = class(GenericClassInstance,'GenericClass');
end

View file

@ -0,0 +1,4 @@
%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end

View file

@ -0,0 +1,4 @@
%Set function
function GenericClassInstance = setValue(GenericClassInstance,newValue)
GenericClassInstance.classVariable = newValue;
end

View file

@ -0,0 +1,3 @@
function display(GenericClassInstance)
disp(sprintf('%f',GenericClassInstance.classVariable));
end

View file

@ -0,0 +1,9 @@
>> myClass = GenericClass(3)
3.000000
>> myClass = setValue(myClass,pi)
3.141593
>> getValue(myClass)
ans =
3.141592653589793

View file

@ -0,0 +1,28 @@
classdef GenericClass2
properties
classVariable
end %properties
methods
%Class constructor
function objectInstance = GenericClass2(varargin)
if isempty(varargin) %No input arguments
objectInstance.classVariable = 0;
else
objectInstance.classVariable = varargin{1};
end
end
%Set function
function setValue(GenericClassInstance,newValue)
GenericClassInstance.classVariable = newValue;
%MATLAB magic that changes the object in the scope that called
%this set function.
assignin('caller',inputname(1),GenericClassInstance);
end
end %methods
end

View file

@ -0,0 +1,4 @@
%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end

View file

@ -0,0 +1,3 @@
function display(GenericClassInstance)
disp(sprintf('%f',GenericClassInstance.classVariable));
end

Some files were not shown because too many files have changed in this diff Show more