Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

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

View file

@ -0,0 +1,13 @@
'''Abstract type''' is a type without instances or without definition.
For example in [[object-oriented programming]] using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called '''interfaces'''. In the languages that do not support multiple [[inheritance]] ([[Ada]], [[Java]]), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like [[C++]]) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, [[object-oriented programming | OO]] languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).
The term '''abstract datatype''' also may denote a type, with an implementation provided by the programmer rather than directly by the language (a '''built-in''' or an inferred type). Here the word ''abstract'' means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the [[wp:Information_hiding|information hiding principle]].
It is important not to confuse this ''abstractness'' (of implementation) with one of the '''abstract type'''. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.
In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have '''abstract types''' that are not OO related and are not an abstractness too. These are ''pure abstract types'' without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter. <!-- An OCaml Guru would explain this better than me, a poor beginner... -->
'''Task''': show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both.

View file

@ -0,0 +1,6 @@
T AbstractQueue
F.virtual.abstract enqueue(Int item) -> N
T PrintQueue(AbstractQueue)
F.virtual.assign enqueue(Int item) -> N
print(item)

View file

@ -0,0 +1,13 @@
class abs definition abstract.
public section.
methods method1 abstract importing iv_value type f exporting ev_ret type i.
protected section.
methods method2 abstract importing iv_name type string exporting ev_ret type i.
methods add importing iv_a type i iv_b type i exporting ev_ret type i.
endclass.
class abs implementation.
method add.
ev_ret = iv_a + iv_b.
endmethod.
endclass.

View file

@ -0,0 +1,5 @@
interface inter.
methods: method1 importing iv_value type f exporting ev_ret type i,
method2 importing iv_name type string exporting ev_ret type i,
add importing iv_a type i iv_b type i exporting ev_ret type i.
endinterface.

View file

@ -0,0 +1,8 @@
package
{
public interface IInterface
{
function method1():void;
function method2(arg1:Array, arg2:Boolean):uint;
}
}

View file

@ -0,0 +1,22 @@
package {
import flash.utils.getQualifiedClassName;
public class AbstractClass {
private static const FULLY_QUALIFIED_NAME:String = "AbstractClass";
// For classes in a package, the fully qualified name should be in the form "package.name::class_name"
// Note that a double colon and not a dot is used before the class name. This is the format returned
// by the getQualifiedClassName() function.
public function AbstractClass() {
if ( getQualifiedClassName(this) == FULLY_QUALIFIED_NAME )
throw new Error("Class " + FULLY_QUALIFIED_NAME + " is abstract.");
}
public function abstractMethod(a:int, b:int):void {
throw new Error("abstractMethod is not implemented.");
}
}
}

View file

@ -0,0 +1,10 @@
package {
public class Example extends AbstractClass {
override public function abstractMethod(a:int, b:int):void {
trace(a + b);
}
}
}

View file

@ -0,0 +1,3 @@
type Queue is limited interface;
procedure Enqueue (Lounge : in out Queue; Item : in out Element) is abstract;
procedure Dequeue (Lounge : in out Queue; Item : in out Element) is abstract;

View file

@ -0,0 +1,2 @@
type Scheduler is task interface;
procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;

View file

@ -0,0 +1,10 @@
with Ada.Finalization;
...
type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
Previous : not null access Node'Class := Node'Unchecked_Access;
Next : not null access Node'Class := Node'Unchecked_Access;
end record;
overriding procedure Finalize (X : in out Node); -- Removes the node from its list if any
overriding procedure Dequeue (Lounge : in out Node; Item : in out Element);
overriding procedure Enqueue (Lounge : in out Node; Item : in out Element);
procedure Process (X : in out Node) is abstract; -- To be implemented

View file

@ -0,0 +1,53 @@
module AbstractInterfaceExample where
open import Function
open import Data.Bool
open import Data.String
-- * One-parameter interface for the type `a' with only one method.
record VoiceInterface (a : Set) : Set where
constructor voice-interface
field say-method-of : a String
open VoiceInterface
-- * An overloaded method.
say : {a : Set} _ : VoiceInterface a a String
say instance = say-method-of instance
-- * Some data types.
data Cat : Set where
cat : Bool Cat
crazy! = true
plain-cat = false
-- | This cat is crazy?
crazy? : Cat Bool
crazy? (cat x) = x
-- | A 'plain' dog.
data Dog : Set where
dog : Dog
-- * Implementation of the interface (and method).
instance-for-cat : VoiceInterface Cat
instance-for-cat = voice-interface case where
case : Cat String
case x with crazy? x
... | true = "meeeoooowwwww!!!"
... | false = "meow!"
instance-for-dog : VoiceInterface Dog
instance-for-dog = voice-interface $ const "woof!"
-- * and then:
--
-- say dog => "woof!"
-- say (cat crazy!) => "meeeoooowwwww!!!"
-- say (cat plain-cat) => "meow!"
--

View file

@ -0,0 +1,5 @@
class Abs {
public function method1...
public function method2...
}

View file

@ -0,0 +1,5 @@
interface Inter {
function isFatal : integer
function operate (para : integer = 0)
operator -> (stream, isout)
}

View file

@ -0,0 +1,19 @@
OBJECT fruit
ENDOBJECT
PROC color OF fruit IS EMPTY
OBJECT apple OF fruit
ENDOBJECT
PROC color OF apple IS WriteF('red ')
OBJECT orange OF fruit
ENDOBJECT
PROC color OF orange IS WriteF('orange ')
PROC main()
DEF a:PTR TO apple,o:PTR TO orange,x:PTR TO fruit
FORALL({x},[NEW a, NEW o],`x.color())
ENDPROC

View file

@ -0,0 +1,23 @@
// Interface
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}
// One implementation of the interface for customers
public class CustomerPurchaseOrder implements PurchaseOrder {
public Double discount() {
return .05; // Flat 5% discount
}
}
// Abstract Class
public abstract class AbstractExampleClass {
protected abstract Integer abstractMethod();
}
// Complete the abstract class by implementing its abstract method
public class Class1 extends AbstractExampleClass {
public override Integer abstractMethod() { return 5; }
}

View file

@ -0,0 +1,38 @@
use std
(: abstract class :)
class Abs
text name
AbsIface iface
class AbsIface
function(Abs)(int)->int method
let Abs_Iface = Cdata AbsIface@ {.method = nil}
.: new Abs :. -> Abs {let a = new(Abs); a.iface = Abs_Iface; a}
=: <Abs self>.method <int i> := -> int
(self.iface.method is nil) ? 0 , (call self.iface.method with self i)
(: implementation :)
class Sub <- Abs { int value }
let Sub_Iface = Cdata AbsIface@ {.method = (code of (nil the Sub).method 0)}
.: new Sub (<int value = -1>) :. -> Sub
let s = new (Sub)
s.iface = Sub_Iface
s.value = value
s
.: <Sub this>.method <int i> :. -> int {this.value + i}
(: example use :)
.:foobar<Abs a>:. {print a.method 12 ; del a}
foobar (new Sub 34) (: prints 46 :)
foobar (new Sub) (: prints 11 :)
foobar (new Abs) (: prints 0 :)

View file

@ -0,0 +1,28 @@
color(r, g, b){
static color
If !color
color := Object("base", Object("R", r, "G", g, "B", b
,"GetRGB", "Color_GetRGB"))
return Object("base", Color)
}
Color_GetRGB(clr) {
return "not implemented"
}
waterColor(r, g, b){
static waterColor
If !waterColor
waterColor := Object("base", color(r, g, b),"GetRGB", "WaterColor_GetRGB")
return Object("base", WaterColor)
}
WaterColor_GetRGB(clr){
return clr.R << 16 | clr.G << 8 | clr.B
}
test:
blue := color(0, 0, 255)
msgbox % blue.GetRGB() ; displays "not implemented"
blue := waterColor(0, 0, 255)
msgbox % blue.GetRGB() ; displays 255
return

View file

@ -0,0 +1,19 @@
INSTALL @lib$+"CLASSLIB"
REM Declare a class with no implementation:
DIM abstract{method}
PROC_class(abstract{})
REM Inherit from the abstract class:
DIM derived{member%}
PROC_inherit(derived{}, abstract{})
PROC_class(derived{})
REM Provide an implementation for the derived class:
DEF derived.method : PRINT "Hello world!" : ENDPROC
REM Instantiate the derived class:
PROC_new(instance{}, derived{})
REM Test by calling the method:
PROC(instance.method)

View file

@ -0,0 +1,7 @@
class Abs {
public:
virtual int method1(double value) = 0;
virtual int add(int a, int b){
return a+b;
}
};

View file

@ -0,0 +1,9 @@
abstract class Class1
{
public abstract void method1();
public int method2()
{
return 0;
}
}

View file

@ -0,0 +1,33 @@
#ifndef INTERFACE_ABS
#define INTERFACE_ABS
typedef struct sAbstractCls *AbsCls;
typedef struct sAbstractMethods {
int (*method1)(AbsCls c, int a);
const char *(*method2)(AbsCls c, int b);
void (*method3)(AbsCls c, double d);
} *AbstractMethods, sAbsMethods;
struct sAbstractCls {
AbstractMethods klass;
void *instData;
};
#define ABSTRACT_METHODS( cName, m1, m2, m3 ) \
static sAbsMethods cName ## _Iface = { &m1, &m2, &m3 }; \
AbsCls cName ## _Instance( void *clInst) { \
AbsCls ac = malloc(sizeof(struct sAbstractCls)); \
if (ac) { \
ac->klass = &cName ## _Iface; \
ac->instData = clInst; \
}\
return ac; }
#define Abs_Method1( c, a) (c)->klass->method1(c, a)
#define Abs_Method2( c, b) (c)->klass->method2(c, b)
#define Abs_Method3( c, d) (c)->klass->method3(c, d)
#define Abs_Free(c) \
do { if (c) { free((c)->instData); free(c); } } while(0);
#endif

View file

@ -0,0 +1,10 @@
#ifndef SILLY_H
#define SILLY_H
#include "intefaceAbs.h"
#include <stdlib.h>
typedef struct sillyStruct *Silly;
extern Silly NewSilly( double, const char *);
extern AbsCls Silly_Instance(void *);
#endif

View file

@ -0,0 +1,41 @@
#include "silly.h"
#include <string.h>
#include <stdio.h>
struct sillyStruct {
double v1;
char str[32];
};
Silly NewSilly(double vInit, const char *strInit)
{
Silly sily = malloc(sizeof( struct sillyStruct ));
sily->v1 = vInit;
sily->str[0] = '\0';
strncat(sily->str, strInit, 31);
return sily;
}
static
int MyMethod1( AbsCls c, int a)
{
Silly s = (Silly)(c->instData);
return a+strlen(s->str);
}
static
const char *MyMethod2(AbsCls c, int b)
{
Silly s = (Silly)(c->instData);
sprintf(s->str, "%d", b);
return s->str;
}
static
void MyMethod3(AbsCls c, double d)
{
Silly s = (Silly)(c->instData);
printf("InMyMethod3, %f\n",s->v1 * d);
}
ABSTRACT_METHODS( Silly, MyMethod1, MyMethod2, MyMethod3)

View file

@ -0,0 +1,13 @@
#include <stdio.h>
#include "silly.h"
int main()
{
AbsCls abster = Silly_Instance(NewSilly( 10.1, "Green Tomato"));
printf("AbsMethod1: %d\n", Abs_Method1(abster, 5));
printf("AbsMethod2: %s\n", Abs_Method2(abster, 4));
Abs_Method3(abster, 21.55);
Abs_Free(abster);
return 0;
}

View file

@ -0,0 +1,58 @@
INTERFACE-ID. Shape.
PROCEDURE DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
END METHOD perimeter.
METHOD-ID. shape-area.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
END METHOD shape-area.
END INTERFACE Shape.
CLASS-ID. Rectangle.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
INTERFACE Shape.
OBJECT IMPLEMENTS Shape.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 width USAGE FLOAT-LONG PROPERTY.
01 height USAGE FLOAT-LONG PROPERTY.
PROCEDURE DIVISION.
METHOD-ID. perimeter.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * 2.0 + height * 2.0
GOBACK
.
END METHOD perimeter.
METHOD-ID. shape-area.
DATA DIVISION.
LINKAGE SECTION.
01 ret USAGE FLOAT-LONG.
PROCEDURE DIVISION RETURNING ret.
COMPUTE ret = width * height
GOBACK
.
END METHOD shape-area.
END OBJECT.
END CLASS Rectangle.

View file

@ -0,0 +1 @@
(defprotocol Foo (foo [this]))

View file

@ -0,0 +1,13 @@
(defgeneric kar (kons)
(:documentation "Return the kar of a kons."))
(defgeneric kdr (kons)
(:documentation "Return the kdr of a kons."))
(defun konsp (object &aux (args (list object)))
"True if there are applicable methods for kar and kdr on object."
(not (or (endp (compute-applicable-methods #'kar args))
(endp (compute-applicable-methods #'kdr args)))))
(deftype kons ()
'(satisfies konsp))

View file

@ -0,0 +1,10 @@
(defmethod kar ((cons cons))
(car cons))
(defmethod kdr ((cons cons))
(cdr cons))
(konsp (cons 1 2)) ; => t
(typep (cons 1 2) 'kons) ; => t
(kar (cons 1 2)) ; => 1
(kdr (cons 1 2)) ; => 2

View file

@ -0,0 +1,11 @@
(defmethod kar ((n integer))
1)
(defmethod kdr ((n integer))
(if (zerop n) nil
(1- n)))
(konsp 45) ; => t
(typep 45 'kons) ; => t
(kar 45) ; => 1
(kdr 45) ; => 44

View file

@ -0,0 +1,11 @@
(* Abstract type *)
Object = POINTER TO ABSTRACT RECORD END;
(* Integer inherits Object *)
Integer = POINTER TO RECORD (Object)
i: INTEGER
END;
(* Point inherits Object *)
Point = POINTER TO RECORD (Object)
x,y: REAL
END;

View file

@ -0,0 +1,15 @@
(* Abstract method of Object *)
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
(* Implementation of the abstract method Show() in class Integer *)
PROCEDURE (i: Integer) Show*;
BEGIN
StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln
END Show;
(* Implementation of the abstract method Show() in class Point *)
PROCEDURE (p: Point) Show*;
BEGIN
StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(',');
StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
END Show;

View file

@ -0,0 +1,40 @@
abstract class Animal # only abstract class can have abstract methods
abstract def move
abstract def think
# abstract class can have normal fields and methods
def initialize(@name : String)
end
def process
think
move
end
end
# WalkingAnimal still have to be declared abstract because `think` was not implemented
abstract class WalkingAnimal < Animal
def move
puts "#{@name} walks"
end
end
class Human < WalkingAnimal
property in_car = false
def move
if in_car
puts "#{@name} drives a car"
else
super
end
end
def think
puts "#{@name} thinks"
end
end
# Animal.new # => can't instantiate abstract class
he = Human.new("Andrew") # ok
he.process

View file

@ -0,0 +1,27 @@
import std.stdio;
class Foo {
// abstract methods can have an implementation for
// use in super calls.
abstract void foo() {
writeln("Test");
}
}
interface Bar {
void bar();
// Final interface methods are allowed.
final int spam() { return 1; }
}
class Baz : Foo, Bar { // Super class must come first.
override void foo() {
writefln("Meep");
super.foo();
}
void bar() {}
}
void main() {}

View file

@ -0,0 +1,3 @@
TSomeClass = class abstract (TObject)
...
end;

View file

@ -0,0 +1,13 @@
type
TMyObject = class(TObject)
public
procedure AbstractFunction; virtual; abstract; // Your virtual abstract function to overwrite in descendant
procedure ConcreteFunction; virtual; // Concrete function calling the abstract function
end;
implementation
procedure TMyObject.ConcreteFunction;
begin
AbstractFunction; // Calling the abstract function
end;

View file

@ -0,0 +1,3 @@
interface Foo {
to bar(a :int, b :int)
}

View file

@ -0,0 +1,9 @@
interface Foo guards FooStamp {
to bar(a :int, b :int)
}
def x implements FooStamp {
to bar(a :int, b :int) {
return a - b
}
}

View file

@ -0,0 +1,37 @@
^|EMal doesn't support abstract types with partial implementations,
|but can use interfaces.
|^
type Beast
interface
fun getKind = text by block do end
fun getName = text by block do end
fun getCry = text by block do end
end
type Dog implements Beast
model
text kind
text name
fun getKind = text by block do return me.kind end
fun getName = text by block do return me.name end
fun getCry = text by block do return "Woof" end
end
type Cat implements Beast
model
text kind
text name
fun getKind = text by block do return me.kind end
fun getName = text by block do return me.name end
fun getCry = text by block do return "Meow" end
end
type AbstractType
^|Beast b = Beast() # interface instantiation is not allowed|^
fun bprint = void by Beast b
writeLine(b.getName() + ", who's a " + b.getKind() + ", cries: " + b.getCry() + ".")
end
^|instantiation works because a positional variadic constructor
|has been auto generated
|^
var d = Dog("labrador", "Max")
Cat c = Cat("siamese", "Sammy")
bprint(d)
bprint(c)

View file

@ -0,0 +1,17 @@
deferred class
AN_ABSTRACT_CLASS
feature
a_deferred_feature
-- a feature whose implementation is left to a descendent
deferred
end
an_effective_feature: STRING
-- deferred (abstract) classes may still include effective features
do
Result := "I am implemented!"
end
end

View file

@ -0,0 +1,61 @@
note
title: "Prototype Person"
description: "Abstract notion of a {PERSON}."
synopsis: "[
Abstract Data Types as represented by any Eiffel class, fully or partially implemented, are
not just about the attribute and routine features of the class (deferred or implemented).
The class and each feature may also have specification rules expressed as preconditions,
post-conditions, and class invariants. Other assertion contracts may be applied to fully
implemented features as well.
In the example below, while `age' is deferred (i.e. "abstract"), we have coded a rule which
states that any caller of `age' must only do so after a `birth_date' has been defined and
attached to that feature. Failing to do so will cause a contract violation. Moreover, the
class invariant makes two strong assertions that must always hold for any implemented version
of {PERSON}: The `birth_date' (if attached--that is--not Void or null) must be in the past
and never in the future. Also, if "Years" are used to represent the age, the calculation of
`age' must always agree with "current year - birth year = age".
This form of Abstract Data Type specification has very clear advantages in that not only
must client code or descendents conform statically, implementing what is deferred, but they
must also obey the rules of the assertions dynamically in a polymorphic run-time situation.
]"
deferred class
PERSON
feature -- Access
first_name,
last_name,
middle_name,
suffix: STRING
birth_date: detachable DATE
-- Date-of-Birth for Current {PERSON}.
deferred
end
feature -- Basic Operations
age: NATURAL_64
-- Age of Current {PERSON} in some undefined units.
require
has_birth_date: attached birth_date
deferred
end
age_units: STRING
-- Unit-of-Measure (UOM) of `age'.
attribute
Result := year_unit_string
end
year_unit_string: STRING = "Years"
invariant
not_future: attached birth_date as al_birth_date implies al_birth_date < (create {DATE}.make_now)
accurate_age: attached birth_date as al_birth_date and then age > 0 and then age_units.same_string (year_unit_string)
implies ((create {DATE}.make_now).year - al_birth_date.year) = age
end

View file

@ -0,0 +1,4 @@
abstract class Bike
{
abstract run();
}

View file

@ -0,0 +1,8 @@
type Shape =
abstract Perimeter: unit -> float
abstract Area: unit -> float
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,16 @@
[<AbstractClass>]
type Bird() =
// an abstract (=virtual) method with default impl.
abstract Move : unit -> unit
default x.Move() = printfn "flying"
// a pure virtual method
abstract Sing: unit -> string
type Blackbird() =
inherit Bird()
override x.Sing() = "tra-la-la"
type Ostrich() =
inherit Bird()
override x.Move() = printfn "walking"
override x.Sing() = "hiss hiss!"

View file

@ -0,0 +1,28 @@
abstract class X
{
Void method1 ()
{
echo ("Method 1 in X")
}
abstract Void method2 ()
}
class Y : X
{
// Y must override the abstract method in X
override Void method2 ()
{
echo ("Method 2 in Y")
}
}
class Main
{
public static Void main ()
{
y := Y()
y.method1
y.method2
}
}

View file

@ -0,0 +1,25 @@
include 4pp/lib/foos.4pp
:: X()
class
method: method1
method: method2
end-class {
:method { ." Method 1 in X" cr } ; defines method1
}
;
:: Y()
extends X()
end-extends {
:method { ." Method 2 in Y" cr } ; defines method2
}
;
: Main
static Y() y
y => method1
y => method2
;
Main

View file

@ -0,0 +1,3 @@
include FMS-SI.f
The FMS object extension uses duck typing and so has no need for abstract types.

View file

@ -0,0 +1,16 @@
! abstract derived type
type, abstract :: TFigure
real(rdp) :: area
contains
! deferred method i.e. abstract method = must be overridden in extended type
procedure(calculate_area), deferred, pass :: calculate_area
end type TFigure
! only declaration of the abstract method/procedure for TFigure type
abstract interface
function calculate_area(this)
import TFigure !imports TFigure type from host scoping unit and makes it accessible here
implicit none
class(TFigure) :: this
real(rdp) :: calculate_area
end function calculate_area
end interface

View file

@ -0,0 +1,43 @@
' FB 1.05.0 Win64
Type Animal Extends Object
Declare Abstract Sub MakeNoise()
End Type
Type Bear Extends Animal
name As String
Declare Constructor(name As String)
Declare Sub MakeNoise()
End Type
Constructor Bear(name As String)
This.name = name
End Constructor
Sub Bear.MakeNoise()
Print name; " is growling"
End Sub
Type Dog Extends Animal
name As String
Declare Constructor(name As String)
Declare Sub MakeNoise()
End Type
Constructor Dog(name As String)
This.name = name
End Constructor
Sub Dog.MakeNoise()
Print name; " is barking"
End Sub
Dim b As Animal Ptr = New Bear("Bruno")
b -> MakeNoise()
Dim d As Animal Ptr = New Dog("Rover")
d -> MakeNoise()
Delete b
Delete d
Print
Print "Press any key to quit program"
Sleep

View file

@ -0,0 +1,4 @@
class AbstractStack()
def .valid?(object) nil
tag AbstractStack some-object # always fails

View file

@ -0,0 +1,8 @@
class StackInterface()
def .valid?(object)
object
and
bound? .enstack
is-instance? .enstack Closure
bound? .destack
is-instance? .destack Closure

View file

@ -0,0 +1,9 @@
class XYZstack(Object)
def .init()
var .items ()
def .enstack(object)
setq .items (cons object .items)
def .destack()
var tmp (car .items)
setq .items (cdr .items)
tmp

View file

@ -0,0 +1 @@
tag StackInterface (XYZstack(.new))

View file

@ -0,0 +1,42 @@
package main
import "fmt"
type Beast interface {
Kind() string
Name() string
Cry() string
}
type Dog struct {
kind string
name string
}
func (d Dog) Kind() string { return d.kind }
func (d Dog) Name() string { return d.name }
func (d Dog) Cry() string { return "Woof" }
type Cat struct {
kind string
name string
}
func (c Cat) Kind() string { return c.kind }
func (c Cat) Name() string { return c.name }
func (c Cat) Cry() string { return "Meow" }
func bprint(b Beast) {
fmt.Printf("%s, who's a %s, cries: %q.\n", b.Name(), b.Kind(), b.Cry())
}
func main() {
d := Dog{"labrador", "Max"}
c := Cat{"siamese", "Sammy"}
bprint(d)
bprint(c)
}

View file

@ -0,0 +1,5 @@
public interface Interface {
int method1(double value)
int method2(String name)
int add(int a, int b)
}

View file

@ -0,0 +1,5 @@
public abstract class Abstract1 {
abstract public int methodA(Date value)
abstract protected int methodB(String name)
int add(int a, int b) { a + b }
}

View file

@ -0,0 +1,3 @@
public abstract class Abstract2 implements Interface {
int add(int a, int b) { a + b }
}

View file

@ -0,0 +1,15 @@
public class Concrete1 implements Interface {
public int method1(double value) { value as int }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
public int add(int a, int b) { a + b }
}
public class Concrete2 extends Abstract1 {
public int methodA(Date value) { value.toCalendar()[Calendar.DAY_OF_YEAR] }
protected int methodB(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
}
public class Concrete3 extends Abstract2 {
public int method1(double value) { value as int }
public int method2(String name) { (! name) ? 0 : name.toList().collect { it as char }.sum() }
}

View file

@ -0,0 +1,12 @@
def c1 = new Concrete1()
assert c1 instanceof Interface
println (new Concrete1().method2("Superman"))
def c2 = new Concrete2()
assert c2 instanceof Abstract1
println (new Concrete2().methodB("Spiderman"))
def c3 = new Concrete3()
assert c3 instanceof Interface
assert c3 instanceof Abstract2
println (new Concrete3().method2("Hellboy"))

View file

@ -0,0 +1,3 @@
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool

View file

@ -0,0 +1,5 @@
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)

View file

@ -0,0 +1,2 @@
func :: (Eq a) => a -> Bool
func x = x == x

View file

@ -0,0 +1 @@
data Foo = Foo {x :: Integer, str :: String}

View file

@ -0,0 +1,3 @@
instance Eq Foo where
(Foo x1 str1) == (Foo x2 str2) =
(x1 == x2) && (str1 == str2)

View file

@ -0,0 +1,3 @@
class abstraction()
abstract method compare(l,r) # generates runerr(700, "method compare()")
end

View file

@ -0,0 +1,14 @@
interface Example {
String stringA = "rosetta";
String stringB = "code";
private String methodA() {
return stringA + " " + stringB;
}
default int methodB(int value) {
return value + 100;
}
int methodC(int valueA, int valueB);
}

View file

@ -0,0 +1,9 @@
class ExampleImpl implements Example {
public int methodB(int value) {
return value + 200;
}
public int methodC(int valueA, int valueB) {
return valueA + valueB;
}
}

View file

@ -0,0 +1,14 @@
abstract class Example {
String stringA = "rosetta";
String stringB = "code";
private String methodA() {
return stringA + " " + stringB;
}
protected int methodB(int value) {
return value + 100;
}
public abstract int methodC(int valueA, int valueB);
}

View file

@ -0,0 +1,5 @@
class ExampleImpl extends Example {
public int methodC(int valueA, int valueB) {
return valueA + valueB;
}
}

View file

@ -0,0 +1,39 @@
def Beast::new($kind; $name): {
superclass: "Beast",
class: null,
$kind,
$name,
cry: "unspecified"
};
def Ape::new($kind; $name):
Beast::new($kind; $name)
| .class = "Ape"
| .cry = "Hoot";
def Cat::new($kind; $name):
Beast::new($kind; $name)
| .class = "Cat"
| .cry = "Meow";
def Dog::new($kind; $name):
Beast::new($kind; $name)
| .class = "Dog"
| .cry = "Woof";
def print:
def a($noun):
$noun
| if .[0:1] | test("[aeio]") then "an \(.)" else "a \(.)" end;
if .class == null
then "\(.name) is \(a(.kind)), which is an unknown type of \(.superclass)."
else "\(.name) is \(a(.kind)), a type of \(.class), and cries: \(.cry)."
end;
Beast::new("sasquatch"; "Bigfoot"),
Ape::new("chimpanzee"; "Nim Chimsky"),
Dog::new("labrador"; "Max"),
Cat::new("siamese"; "Sammy")
| print

View file

@ -0,0 +1,2 @@
abstract type «name» end
abstract type «name» <: «supertype» end

View file

@ -0,0 +1,6 @@
abstract type Number end
abstract type Real <: Number end
abstract type FloatingPoint <: Real end
abstract type Integer <: Real end
abstract type Signed <: Integer end
abstract type Unsigned <: Integer end

View file

@ -0,0 +1,55 @@
// version 1.1
interface Announcer {
fun announceType()
// interface can contain non-abstract members but cannot store state
fun announceName() {
println("I don't have a name")
}
}
abstract class Animal: Announcer {
abstract fun makeNoise()
// abstract class can contain non-abstract members
override fun announceType() {
println("I am an Animal")
}
}
class Dog(private val name: String) : Animal() {
override fun makeNoise() {
println("Woof!")
}
override fun announceName() {
println("I'm called $name")
}
}
class Cat: Animal() {
override fun makeNoise() {
println("Meow!")
}
override fun announceType() {
println("I am a Cat")
}
}
fun main(args: Array<String>) {
val d = Dog("Fido")
with(d) {
makeNoise()
announceType() // inherits Animal's implementation
announceName()
}
println()
val c = Cat()
with(c) {
makeNoise()
announceType()
announceName() // inherits Announcer's implementation
}
}

View file

@ -0,0 +1,21 @@
define abstract_trait => trait {
require get(index::integer)
provide first() => .get(1)
provide second() => .get(2)
provide third() => .get(3)
provide fourth() => .get(4)
}
define my_type => type {
parent array
trait { import abstract_trait }
public onCreate(...) => ..onCreate(:#rest)
}
local(test) = my_type('a','b','c','d','e')
#test->first + "\n"
#test->second + "\n"
#test->third + "\n"
#test->fourth + "\n"

View file

@ -0,0 +1,5 @@
on extendAbstractClass (instance, abstractClass)
-- 'raw' instance of abstract class is made parent ("ancestor") of the
-- passed instance, i.e. the passed instance extends the abstract class
instance.setProp(#ancestor, abstractClass.rawNew())
end

View file

@ -0,0 +1,12 @@
-- instantiation of abstract class by calling its constructor fails
on new (me)
-- optional: show error message as alert
_player.alert("Error:"&&me.script&&" is an abstract class")
return VOID
end
on ring (me, n)
repeat with i = 1 to n
put me.ringtone
end repeat
end

View file

@ -0,0 +1,11 @@
property ringtone
on new (me)
extendAbstractClass(me, script("AbstractClass"))
me.ringtone = "Bell"
return me
end
on foo (me)
put "FOO"
end

View file

@ -0,0 +1,10 @@
obj = script("MyClass").new()
obj.ring(3)
-- "Bell"
-- "Bell"
-- "Bell"
-- this fails
test = script("AbstractClass").new()
put test
-- <Void>

View file

@ -0,0 +1,12 @@
on implementsInterface (instance, interfaceClass)
interfaceFuncs = interfaceClass.handlers()
funcs = instance.handlers()
repeat with f in interfaceFuncs
if funcs.getPos(f)=0 then
-- optional: show error message as alert
_player.alert("Error:"&&instance.script&&"doesn't implement interface"&&interfaceClass)
return FALSE
end if
end repeat
return TRUE
end

View file

@ -0,0 +1,3 @@
on foo
on bar
on foobar

View file

@ -0,0 +1,20 @@
on new (me)
-- if this class doesn't implement all functions of the
-- interface class, instantiation fails
if not implementsInterface(me, script("InterfaceClass")) then
return VOID
end if
return me
end
on foo (me)
put "FOO"
end
on bar (me)
put "BAR"
end
on foobar (me)
put "FOOBAR"
end

View file

@ -0,0 +1,3 @@
obj = script("MyClass").new()
put obj -- would show <Void> if interface is not fully implemented
-- <offspring "MyClass" 2 171868>

View file

@ -0,0 +1,9 @@
:- protocol(datep).
:- public(today/3).
:- public(leap_year/1).
:- public(name_of_day/3).
:- public(name_of_month/3).
:- public(days_in_month/3).
:- end_protocol.

View file

@ -0,0 +1,34 @@
BaseClass = {}
function class ( baseClass )
local new_class = {}
local class_mt = { __index = new_class }
function new_class:new()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
if not baseClass then baseClass = BaseClass end
setmetatable( new_class, { __index = baseClass } )
return new_class
end
function abstractClass ( self )
local new_class = {}
local class_mt = { __index = new_class }
function new_class:new()
error("Abstract classes cannot be instantiated")
end
if not baseClass then baseClass = BaseClass end
setmetatable( new_class, { __index = baseClass } )
return new_class
end
BaseClass.class = class
BaseClass.abstractClass = abstractClass

View file

@ -0,0 +1,8 @@
A = class() -- New class A inherits BaseClass by default
AA = A:class() -- New class AA inherits from existing class A
B = abstractClass() -- New abstract class B
BB = B:class() -- BB is not abstract
A:new() -- Okay: New class instance
AA:new() -- Okay: New class instance
B:new() -- Error: B is abstract
BB:new() -- Okay: BB is not abstract

View file

@ -0,0 +1,63 @@
Class BaseState {
Private:
      x as double=1212, z1 as currency=1000, k$="ok"
      Module Err {
                  Module "Class.BaseState"
                  Error "not implement yet"
      }      
}
Class AbstractOne {
Public:
      Group z {
            Value {
                  Link parent z1 to z1
                  =z1
            }
      }
      Function M(k as double) {
            .Err
      }
      Module AddCurrency (k as currency) {
            .Err
      }
      Function GetString$ {
            .Err
      }
Class:
      Module AbstractOne {
                  If Not Match("G") Then Exit
                  Read x
                  \\ combine x with This
                  This=x
      }
}
\\ create new group as K
K=AbstractOne(BaseState())
Try  ok {
      Print K.GetString$()
}
If Not ok Then Print Error$
\\ Now Add final functions/modules
Group k {
      Function Final M(k as double) {
            =.x*k
      }
      Module Final AddCurrency (k as currency) {
            .z1+=k
      }
      Function Final GetString$ {
            =.K$
      }       
}
Print k.M(100), k.GetString$()
K.AddCurrency 50.12
Def ExpType$(x)=Type$(x)
Print k.z=1050.12, ExpType$(k.z), Type$(k.z) ' true, Currency, Group
\\ Now combine AbstractOne without new BaseState
\\ but because all functions are final in k, nothing combined
k=AbstractOne()
Print k.M(100), k.GetString$()
For k {
      \\ we can use For Object {} and a dot before members to get access
      Print .z=1050.12, ExpType$(.z), Type$(.z) ' true, Currency, Group
}

View file

@ -0,0 +1,3 @@
classdef (Abstract) AbsClass
...
end

View file

@ -0,0 +1,3 @@
methods (Abstract)
abstMethod(obj)
end

View file

@ -0,0 +1,3 @@
properties (Abstract)
AbsProp
end

View file

@ -0,0 +1,26 @@
(* Define an interface, Foo, which requires that the functions Foo, Bar, and Baz be defined *)
InterfaceFooQ[obj_] := ValueQ[Foo[obj]] && ValueQ[Bar[obj]] && ValueQ[Baz[obj]];
PrintFoo[obj_] := Print["Object ", obj, " does not implement interface Foo."];
PrintFoo[obj_?InterfaceFooQ] := Print[
"Foo: ", Foo[obj], "\n",
"Bar: ", Bar[obj], "\n",
"Baz: ", Baz[obj], "\n"];
(* Extend all integers with Interface Foo *)
Foo[x_Integer] := Mod[x, 2];
Bar[x_Integer] := Mod[x, 3];
Baz[x_Integer] := Mod[x, 5];
(* Extend a particular string with Interface Foo *)
Foo["Qux"] = "foo";
Bar["Qux"] = "bar";
Baz["Qux"] = "baz";
(* Print a non-interface object *)
PrintFoo[{"Some", "List"}];
(* And for an integer *)
PrintFoo[8];
(* And for the specific string *)
PrintFoo["Qux"];
(* And finally a non-specific string *)
PrintFoo["foobarbaz"]

View file

@ -0,0 +1,26 @@
:- module eq.
:- interface.
:- typeclass eq(T) where [
pred (T::in) == (T::in) is semidet,
pred (T::in) \= (T::in) is semidet
].
:- pred f(T::in) is semidet <= eq(T).
:- type foo
---> foo(
x :: int,
str :: string
).
:- instance eq(foo).
:- implementation.
f(X) :- X == X.
:- instance eq(foo) where [
A == B :- (A^x = B^x, A^str = B^str),
A \= B :- not A == B
].

View file

@ -0,0 +1,38 @@
using System.Console;
namespace RosettaCode
{
abstract class Fruit
{
abstract public Eat() : void;
abstract public Peel() : void;
virtual public Cut() : void // an abstract class con contain a mixture of abstract and implemented methods
{ // the virtual keyword allows the method to be overridden by derivative classes
WriteLine("Being cut.");
}
}
interface IJuiceable
{
Juice() : void; // interfaces contain only the signatures of methods
}
class Orange : Fruit, IJuiceable
{
public override Eat() : void // implementations of abstract methods need to be marked override
{
WriteLine("Being eaten.");
}
public override Peel() : void
{
WriteLine("Being peeled.");
}
public Juice() : void
{
WriteLine("Being juiced.");
}
}
}

View file

@ -0,0 +1,72 @@
/* NetRexx */
options replace format comments java crossref symbols binary
-- -----------------------------------------------------------------------------
class RCAbstractType public final
method main(args = String[]) public constant
say ' Testing' RCAbstractType.class.getSimpleName
say ' Creating an object of type:' Concrete.class.getSimpleName
conk = Concrete()
say 'getClassName:'.right(20) conk.getClassName
say 'getIfaceName:'.right(20) conk.getIfaceName
say 'mustImplement:'.right(20) conk.mustImplement
say 'canOverride1:'.right(20) conk.canOverride1
say 'canOverride2:'.right(20) conk.canOverride2
say 'callOverridden2:'.right(20) conk.callOverridden2
return
-- -----------------------------------------------------------------------------
class RCAbstractType.Iface interface
ifaceName = RCAbstractType.Iface.class.getSimpleName
method getIfaceName() public returns String
method canOverride1() public returns String
method canOverride2() public returns String
-- -----------------------------------------------------------------------------
class RCAbstractType.Abstraction abstract implements RCAbstractType.Iface
properties inheritable
className = String
method Abstraction() public
setClassName(this.getClass.getSimpleName)
return
method mustImplement() public abstract returns String
method getClassName() public returns String
return className
method setClassName(nm = String) public
className = nm
return
method getIfaceName() public returns String
return RCAbstractType.Iface.ifaceName
method canOverride1() public returns String
return 'In' RCAbstractType.Abstraction.class.getSimpleName'.canOverride1'
method canOverride2() public returns String
return 'In' RCAbstractType.Abstraction.class.getSimpleName'.canOverride2'
-- -----------------------------------------------------------------------------
class RCAbstractType.Concrete extends RCAbstractType.Abstraction
method Concrete() public
super()
return
method mustImplement() public returns String
return 'In' RCAbstractType.Concrete.class.getSimpleName'.mustImplement'
method canOverride2() public returns String
return 'In' RCAbstractType.Concrete.class.getSimpleName'.canOverride2'
method callOverridden2() public returns String
return super.canOverride2

View file

@ -0,0 +1,46 @@
; file: abstract.lsp
; url: http://rosettacode.org/wiki/Abstract_type
; author: oofoe 2012-01-28
; Abstract Shape Class
(new Class 'Shape) ; Derive new class.
(define (Shape:Shape ; Shape constructor.
(pen "X")) ; Default value.
(list (context) ; Assemble data packet.
(list 'pen pen)
(list 'size (args))))
(define (Shape:line x) ; Print out row with 'pen' character.
(dotimes (i x)
(print (lookup 'pen (self))))
(println))
(define (Shape:draw)) ; Placeholder, does nothing.
; Derived Objects
(new Shape 'Box)
(define (Box:draw) ; Override base draw method.
(let ((s (lookup 'size (self))))
(dotimes (i (s 0)) (:line (self) (s 0)))))
(new Shape 'Rectangle)
(define (Rectangle:draw)
(let ((size (lookup 'size (self))))
(dotimes (i (size 1)) (:line (self) (size 0)))))
; Demonstration
(:draw (Shape)) ; Nothing happens.
(println "A box:")
(:draw (Box "O" 5)) ; Create Box object and call draw method.
(println "\nA rectangle:")
(:draw (Rectangle "R" 32 4))
(exit)

View file

@ -0,0 +1,12 @@
type
Comparable = concept x, y
(x < y) is bool
Stack[T] = concept s, var v
s.pop() is T
v.push(T)
s.len is Ordinal
for value in s:
value is T

View file

@ -0,0 +1,18 @@
# Task: abstract type
#
# Methods without implementation are annotated `abstract`.
#
# Abstract classes and interfaces can contain abstract methods and concrete (i.e. non-abstract) methods.
# Abstract classes can also have attributes.
module abstract_type
interface Inter
fun method1: Int is abstract
fun method2: Int do return 1
end
abstract class Abs
fun method1: Int is abstract
fun method2: Int do return 1
var attr: Int
end

View file

@ -0,0 +1,4 @@
class virtual foo =
object
method virtual bar : int
end

View file

@ -0,0 +1 @@
type t

View file

@ -0,0 +1,5 @@
module Foo : sig
type t
end = struct
type t = int * int
end

View file

@ -0,0 +1,5 @@
type u
type v
type 'a t
type ut = u t
type vt = v t

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