new tasks

This commit is contained in:
Ingy döt Net 2013-04-09 00:46:50 -07:00
parent 2a4d27cea0
commit 80737d5a6a
1194 changed files with 15353 additions and 1 deletions

14
Task/Classes/0DESCRIPTION Normal file
View file

@ -0,0 +1,14 @@
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.
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.
The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it.

6
Task/Classes/1META.yaml Normal file
View file

@ -0,0 +1,6 @@
---
category:
- Object oriented
- Type System
- Encyclopedia
note: Basic language learning

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,19 @@
DECLARE SUB MyClassDelete (pthis AS MyClass)
DECLARE SUB MyClassSomeMethod (pthis AS MyClass)
DECLARE SUB MyClassInit (pthis AS MyClass)
TYPE MyClass
Variable AS INTEGER
END TYPE
DIM obj AS MyClass
MyClassInit obj
MyClassSomeMethod obj
SUB MyClassInit (pthis AS MyClass)
pthis.Variable = 0
END SUB
SUB MyClassSomeMethod (pthis AS MyClass)
pthis.Variable = 1
END SUB

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

@ -0,0 +1,30 @@
typedef struct sMyClass
{
int variable;
} *MyClass;
MyClass MyClass_new()
{
MyClass pthis = malloc( sizeof(struct sMyClass) );
//memset(pthis, 0, sizeof(struct sMyClass) );
pthis->variable = 0;
return pthis;
}
void MyClass_delete(MyClass* pthis)
{
if(pthis && *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,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 @@
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,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,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,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,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,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,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,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,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,12 @@
class MyClass {
public static $classVar;
public $instanceVar; // can also initialize it here
function __construct() {
$this->instanceVar = 0;
}
function someMethod() {
$this->instanceVar = 1;
self::$classVar = 3;
}
}
$myObj = new MyClass();

View file

@ -0,0 +1,12 @@
{
package MyClass;
use Moose;
has 'variable' => (is => 'rw', default => 0);
# constructor and accessor methods are added automatically
sub some_method {
my $self = shift;
$self->variable(1);
}
}

View file

@ -0,0 +1,7 @@
use MooseX::Declare;
class MyClass {
has 'variable' => (is => 'rw', default => 0);
method some_method {
$self->variable(1);
}
}

View file

@ -0,0 +1,4 @@
my $instance = MyClass->new; # invoke constructor method
$instance->some_method; # invoke method on object instance
# instance deallocates when the last reference falls out of scope

View file

@ -0,0 +1,19 @@
{
# a class is a package (i.e. a namespace) with methods in it
package MyClass;
# a constructor is a function that returns a blessed reference
sub new {
my $class = shift;
bless {variable => 0}, $class;
# the instance object is a hashref in disguise.
# (it can be a ref to anything.)
}
# an instance method is a function that takes an object as first argument.
# the -> invocation syntax takes care of that nicely, see Usage paragraph below.
sub some_method {
my $self = shift;
$self->{variable} = 1;
}
}

View file

@ -0,0 +1,8 @@
(class +Rectangle)
# dx dy
(dm area> () # Define a a method that calculates the rectangle's area
(* (: dx) (: dy)) )
(println # Create a rectangle, and print its area
(area> (new '(+Rectangle) 'dx 3 'dy 4)) )

View file

@ -0,0 +1,2 @@
class MyClass(object):
...

View file

@ -0,0 +1,38 @@
class MyClass:
name2 = 2 # Class attribute
def __init__(self):
"""
Constructor (Technically an initializer rather than a true "constructor")
"""
self.name1 = 0 # Instance attribute
def someMethod(self):
"""
Method
"""
self.name1 = 1
MyClass.name2 = 3
myclass = MyClass() # class name, invoked as a function is the constructor syntax.
class MyOtherClass:
count = 0 # Population of "MyOtherClass" objects
def __init__(self, name, gender="Male", age=None):
"""
One initializer required, others are optional (with different defaults)
"""
MyOtherClass.count += 1
self.name = name
self.gender = gender
if age is not None:
self.age = age
def __del__(self):
MyOtherClass.count -= 1
person1 = MyOtherClass("John")
print person1.name, person1.gender # "John Male"
print person1.age # Raises AttributeError exception!
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age # "Jane Female 23"

View file

@ -0,0 +1,24 @@
setClass("circle",
representation(
radius="numeric",
centre="numeric"),
prototype(
radius=1,
centre=c(0,0)))
#Instantiate class with some arguments
circS4 <- new("circle", radius=5.5)
#Set other data slots (properties)
circS4@centre <- c(3,4.2)
#Define a method
setMethod("plot", #signature("circle"),
signature(x="circle", y="missing"),
function(x, ...)
{
t <- seq(0, 2*pi, length.out=200)
#Note the use of @ instead of $
plot(x@centre[1] + x@radius*cos(t),
x@centre[2] + x@radius*sin(t),
type="l", ...)
})
plot(circS4)

13
Task/Classes/R/classes.r Normal file
View file

@ -0,0 +1,13 @@
#You define a class simply by setting the class attribute of an object
circS3 <- list(radius=5.5, centre=c(3, 4.2))
class(circS3) <- "circle"
#plot is a generic function, so we can define a class specific method by naming it plot.classname
plot.circle <- function(x, ...)
{
t <- seq(0, 2*pi, length.out=200)
plot(x$centre[1] + x$radius*cos(t),
x$centre[2] + x$radius*sin(t),
type="l", ...)
}
plot(circS3)

View file

@ -0,0 +1,15 @@
#lang racket
(define fish%
(class object%
(super-new)
;; an instance variable & constructor argument
(init-field size)
;; a new method
(define/public (eat)
(displayln "gulp!"))))
;; constructing an instance
(new fish% [size 50])

View file

@ -0,0 +1,26 @@
class MyClass
@@class_var = []
def initialize
# 'initialize' is the constructor method invoked during 'MyClass.new'
@instance_var = 0
end
def some_method
@instance_var = 1
@@class_var << Time.now
end
def self.class_method
# ...
end
# another way to define class methods: define an instance method in this class object's singleton class
class << self
def another_class_method
# ...
end
end
end
myclass = MyClass.new

View file

@ -0,0 +1,12 @@
class MAIN is
main is
test ::= #CLASSTEST(1, 2, 3);
-- the previous line is syntactic sugar for
-- test :CLASSTEST := CLASSTEST::create(1, 2, 3);
#OUT + test.z + "\n"; -- we can access z
test.z := 25; -- we can set z
#OUT + test.x + "\n"; -- we can get x
-- test.x := 5; -- we cannot set x
#OUT + test.getPrivateY(0) + "\n";
end;
end;

View file

@ -0,0 +1,21 @@
class CLASSTEST is
readonly attr x:INT; -- give a public getter, not a setter
private attr y:INT; -- no getter, no setter
attr z:INT; -- getter and setter
-- constructor
create(x, y, z:INT):CLASSTEST is
res :CLASSTEST := new; -- or res ::= new
res.x := x;
res.y := y;
res.z := z;
return res;
end;
-- a getter for the private y summed to s
getPrivateY(s:INT):INT is
-- y is not shadowed so we can write y instead of
-- self.y
return y + s;
end;
end;

View file

@ -0,0 +1,19 @@
/**
* This class implicitly includes a constructor which accepts an int and
* creates "val variable1: Int" with that value.
*/
class MyClass(variable1: Int) {
var variable2 = "asdf" // Another instance variable; a var this time
def this() = this(0) // An auxilliary constructor that instantiates with a default value
def myMethod = variable1 // A getter for variable1
}
/**
* Demonstrate use of our example class.
*/
object Main extends Application {
val m = new MyClass()
val n = new MyClass(3)
println(m.myMethod) // prints 0
println(n.myMethod) // prints 3
}

View file

@ -0,0 +1,14 @@
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUNT"
m))))
dispatch)

View file

@ -0,0 +1,15 @@
Object subclass: #MyClass
instanceVariableNames: 'instanceVar'
classVariableNames: 'classVar'
poolDictionaries: ''
category: 'Testing' !
!MyClass class methodsFor: 'instance creation'!
new
^self basicNew instanceVar := 0 ! !
!MyClass methodsFor: 'testing'!
someMethod
^self instanceVar = 1; classVar = 3 ! !
MyClass new someMethod!

View file

@ -0,0 +1,22 @@
package require TclOO
oo::class create summation {
variable v
constructor {} {
set v 0
}
method add x {
incr v $x
}
method value {} {
return $v
}
destructor {
puts "Ended with value $v"
}
}
set sum [summation new]
puts "Start with [$sum value]"
for {set i 1} {$i <= 10} {incr i} {
puts "Add $i to get [$sum add $i]"
}
$sum destroy