Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
|
||||
note: Object oriented
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
|
||||
|
||||
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at [http://www.devsource.com/article2/0,1759,1928562,00.asp An Exercise in Metaprogramming with Ruby]. This is referred to as "monkeypatching" by Pythonistas and some others.
|
||||
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
var object:Object = new Object();
|
||||
object.foo = "bar";
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package
|
||||
{
|
||||
public dynamic class Foo
|
||||
{
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
var foo:Foo = new Foo();
|
||||
foo.bar = "zap";
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
|
||||
procedure Dynamic is
|
||||
package Abstract_Class is
|
||||
type Class is limited interface;
|
||||
function Boo (X : Class) return String is abstract;
|
||||
end Abstract_Class;
|
||||
use Abstract_Class;
|
||||
|
||||
package Base_Class is
|
||||
type Base is new Class with null record;
|
||||
overriding function Boo (X : Base) return String;
|
||||
end Base_Class;
|
||||
|
||||
package body Base_Class is
|
||||
function Boo (X : Base) return String is
|
||||
begin
|
||||
return "I am Class";
|
||||
end Boo;
|
||||
end Base_Class;
|
||||
use Base_Class;
|
||||
|
||||
E : aliased Base; -- An instance of Base
|
||||
|
||||
begin
|
||||
-- Gone run-time
|
||||
declare
|
||||
type Monkey_Patch (Root : access Base) is new Class with record
|
||||
Foo : Integer := 1;
|
||||
end record;
|
||||
overriding function Boo (X : Monkey_Patch) return String;
|
||||
function Boo (X : Monkey_Patch) return String is
|
||||
begin -- Delegation to the base
|
||||
return X.Root.Boo;
|
||||
end Boo;
|
||||
EE : Monkey_Patch (E'Access); -- Extend E
|
||||
begin
|
||||
Put_Line (EE.Boo & " with" & Integer'Image (EE.Foo));
|
||||
end;
|
||||
end Dynamic;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
define :myClass [name,surname][]
|
||||
|
||||
myInstance: to :myClass ["John" "Doe"]
|
||||
print myInstance
|
||||
|
||||
myInstance\age: 35
|
||||
print myInstance
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
e := {}
|
||||
e.foo := 1
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
INSTALL @lib$+"CLASSLIB"
|
||||
|
||||
REM Create a base class with no members:
|
||||
DIM class{method}
|
||||
PROC_class(class{})
|
||||
|
||||
REM Instantiate the class:
|
||||
PROC_new(myobject{}, class{})
|
||||
|
||||
REM Add a member at run-time:
|
||||
member$ = "mymember#"
|
||||
PROCaddmember(myobject{}, member$, 8)
|
||||
|
||||
REM Test that the member can be accessed:
|
||||
PROCassign("myobject." + member$, "PI")
|
||||
PRINT EVAL("myobject." + member$)
|
||||
END
|
||||
|
||||
DEF PROCaddmember(RETURN obj{}, mem$, size%)
|
||||
LOCAL D%, F%, P%
|
||||
DIM D% DIM(obj{}) + size% - 1, F% LEN(mem$) + 8
|
||||
P% = !^obj{} + 4
|
||||
WHILE !P% : P% = !P% : ENDWHILE : !P% = F%
|
||||
$$(F%+4) = mem$ : F%!(LEN(mem$) + 5) = DIM(obj{})
|
||||
!(^obj{} + 4) = D%
|
||||
ENDPROC
|
||||
|
||||
DEF PROCassign(v$, n$)
|
||||
IF EVAL("FNassign(" + v$ + "," + n$ + ")")
|
||||
ENDPROC
|
||||
DEF FNassign(RETURN n, v) : n = v : = 0
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
( ( struktuur
|
||||
= (aMember=) (aMethod=.!(its.aMember))
|
||||
)
|
||||
& new$struktuur:?object
|
||||
& out$"Object as originally created:"
|
||||
& lst$object
|
||||
& A value:?(object..aMember)
|
||||
& !object:(=?originalMembersAndMethods)
|
||||
& new
|
||||
$ (
|
||||
' ( (anotherMember=)
|
||||
(anotherMethod=.!(its.anotherMember))
|
||||
()$originalMembersAndMethods
|
||||
)
|
||||
)
|
||||
: ?object
|
||||
& out
|
||||
$ "
|
||||
Object with additional member and method and with 'aMember' already set to some interesting value:"
|
||||
& lst$object
|
||||
& some other value:?(object..anotherMember)
|
||||
& out$"
|
||||
Call both methods and output their return values."
|
||||
& out$("aMember contains:" (object..aMethod)$)
|
||||
& out$("anotherMember contains:" (object..anotherMethod)$)
|
||||
&);
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
Object as originally created:
|
||||
(object=
|
||||
=(aMember=) (aMethod=.!(its.aMember)));
|
||||
|
||||
Object with additional member and method and with 'aMember' already set to some interesting value:
|
||||
(object=
|
||||
|
||||
= (anotherMember=)
|
||||
(anotherMethod=.!(its.anotherMember))
|
||||
(aMember=A value)
|
||||
(aMethod=.!(its.aMember)));
|
||||
|
||||
Call both methods and output their return values.
|
||||
aMember contains: A value
|
||||
anotherMember contains: some other value
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
// ----------------------------------------------------------------------------------------------
|
||||
//
|
||||
// Program.cs - DynamicClassVariable
|
||||
//
|
||||
// Mikko Puonti, 2013
|
||||
//
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Dynamic;
|
||||
|
||||
namespace DynamicClassVariable
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
#region Static Members
|
||||
|
||||
private static void Main()
|
||||
{
|
||||
// To enable late binding, we must use dynamic keyword
|
||||
// ExpandoObject readily implements IDynamicMetaObjectProvider which allows us to do some dynamic magic
|
||||
dynamic sampleObj = new ExpandoObject();
|
||||
// Adding a new property
|
||||
sampleObj.bar = 1;
|
||||
Console.WriteLine( "sampleObj.bar = {0}", sampleObj.bar );
|
||||
|
||||
// We can also add dynamically methods and events to expando object
|
||||
// More information: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx
|
||||
// This sample only show very small part of dynamic language features - there is lot's more
|
||||
|
||||
Console.WriteLine( "< Press any key >" );
|
||||
Console.ReadKey();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
# CoffeeScript is dynamic, just like the Javascript it compiles to.
|
||||
# You can dynamically add attributes to objects.
|
||||
|
||||
# First create an object very simply.
|
||||
e = {}
|
||||
e.foo = "bar"
|
||||
e.yo = -> "baz"
|
||||
console.log e.foo, e.yo()
|
||||
|
||||
# CS also has class syntax to instantiate objects, the details of which
|
||||
# aren't shown here. The mechanism to add members is the same, though.
|
||||
class Empty
|
||||
# empty class
|
||||
|
||||
e = new Empty()
|
||||
e.foo = "bar"
|
||||
e.yo = -> "baz"
|
||||
console.log e.foo, e.yo()
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
(defun augment-instance-with-slots (instance slots)
|
||||
(change-class instance
|
||||
(make-instance 'standard-class
|
||||
:direct-superclasses (list (class-of instance))
|
||||
:direct-slots slots)))
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
CL-USER> (let* ((instance (make-instance 'foo :bar 42 :baz 69))
|
||||
(new-slots '((:name xenu :initargs (:xenu)))))
|
||||
(augment-instance-with-slots instance new-slots)
|
||||
(reinitialize-instance instance :xenu 666)
|
||||
(describe instance))
|
||||
#<#<STANDARD-CLASS NIL {1003AEE2C1}> {1003AEE271}>
|
||||
[standard-object]
|
||||
|
||||
Slots with :INSTANCE allocation:
|
||||
BAR = 42
|
||||
BAZ = 69
|
||||
XENU = 666
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
struct Dynamic(T) {
|
||||
private T[string] vars;
|
||||
|
||||
@property T opDispatch(string key)() pure nothrow {
|
||||
return vars[key];
|
||||
}
|
||||
|
||||
@property void opDispatch(string key, U)(U value) pure nothrow {
|
||||
vars[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
import std.variant, std.stdio;
|
||||
|
||||
// If the type of the attributes is known at compile-time:
|
||||
auto d1 = Dynamic!double();
|
||||
d1.first = 10.5;
|
||||
d1.second = 20.2;
|
||||
writeln(d1.first, " ", d1.second);
|
||||
|
||||
|
||||
// If the type of the attributes is mixed:
|
||||
auto d2 = Dynamic!Variant();
|
||||
d2.a = "Hello";
|
||||
d2.b = 11;
|
||||
d2.c = ['x':2, 'y':4];
|
||||
d2.d = (int x) => x ^^ 3;
|
||||
writeln(d2.a, " ", d2.b, " ", d2.c);
|
||||
immutable int x = d2.b.get!int;
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import std.stdio, std.variant, std.conv;
|
||||
|
||||
struct Dyn {
|
||||
Variant[string] data;
|
||||
alias data this;
|
||||
}
|
||||
|
||||
void main(string[] args) {
|
||||
Dyn d;
|
||||
const attribute_name = text("attribute_", args.length);
|
||||
d[attribute_name] = "something";
|
||||
writeln(d[attribute_name]);
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import extensions;
|
||||
|
||||
class Extender : BaseExtender
|
||||
{
|
||||
prop object foo;
|
||||
|
||||
constructor(object)
|
||||
{
|
||||
theObject := object
|
||||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
var object := 234;
|
||||
|
||||
// extending an object with a field
|
||||
object := new Extender(object);
|
||||
|
||||
object.foo := "bar";
|
||||
|
||||
console.printLine(object,".foo=",object.foo);
|
||||
|
||||
console.readChar()
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
#APPTYPE CONSOLE
|
||||
|
||||
CLASS Growable
|
||||
|
||||
PRIVATE:
|
||||
|
||||
DIM instructions AS STRING = "Sleep(1)"
|
||||
:ExecCode
|
||||
DIM dummy AS INTEGER = EXECLINE(instructions, 1)
|
||||
|
||||
PUBLIC:
|
||||
|
||||
METHOD Absorb(code AS STRING)
|
||||
instructions = code
|
||||
GOTO ExecCode
|
||||
END METHOD
|
||||
|
||||
METHOD Yield() AS VARIANT
|
||||
RETURN result
|
||||
END METHOD
|
||||
|
||||
END CLASS
|
||||
|
||||
DIM Sponge AS NEW Growable()
|
||||
|
||||
Sponge.Absorb("DIM b AS VARIANT = 1234567890: DIM result AS VARIANT = b")
|
||||
PRINT Sponge.Yield()
|
||||
Sponge.Absorb("b = ""Hello world!"": result = b")
|
||||
PRINT Sponge.Yield()
|
||||
|
||||
PAUSE
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
vect = [ 'alpha', 'beta', 'gamma' ]
|
||||
vect.dump = function ()
|
||||
for n in [0: self.len()]
|
||||
> @"$(n): ", self[n]
|
||||
end
|
||||
end
|
||||
vect += 'delta'
|
||||
vect.dump()
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
0: alpha
|
||||
1: beta
|
||||
2: gamma
|
||||
3: delta
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
function sub_func( value )
|
||||
self['prop'] -= value
|
||||
return self.prop
|
||||
end
|
||||
|
||||
dict = bless( [
|
||||
'prop' => 0,
|
||||
'add' => function ( value )
|
||||
self.prop += value
|
||||
return self.prop
|
||||
end ,
|
||||
'sub' => sub_func
|
||||
])
|
||||
|
||||
dict[ 'newVar' ] = "I'm Rich In Data"
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
include FMS-SI.f
|
||||
include FMS-SILib.f
|
||||
|
||||
|
||||
|
||||
\ We can add any number of variables at runtime by adding
|
||||
\ objects of any type to an instance at run time. The added
|
||||
\ objects are then accessible via an index number.
|
||||
|
||||
:class foo
|
||||
object-list inst-objects \ a dynamically growable object container
|
||||
:m init: inst-objects init: ;m
|
||||
:m add: ( obj -- ) inst-objects add: ;m
|
||||
:m at: ( idx -- obj ) inst-objects at: ;m
|
||||
;class
|
||||
|
||||
foo foo1
|
||||
|
||||
: main
|
||||
heap> string foo1 add:
|
||||
heap> fvar foo1 add:
|
||||
|
||||
s" Now is the time " 0 foo1 at: !:
|
||||
3.14159e 1 foo1 at: !:
|
||||
|
||||
0 foo1 at: p: \ send the print message to indexed object 0
|
||||
1 foo1 at: p: \ send the print message to indexed object 1
|
||||
;
|
||||
|
||||
main \ => Now is the time 3.14159
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
' Class ... End Class
|
||||
' Esta característica aún no está implementada en el compilador.
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type SomeStruct struct {
|
||||
runtimeFields map[string]string
|
||||
}
|
||||
|
||||
func check(err error) {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
ss := SomeStruct{make(map[string]string)}
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("Create two fields at runtime: ")
|
||||
for i := 1; i <= 2; i++ {
|
||||
fmt.Printf(" Field #%d:\n", i)
|
||||
fmt.Print(" Enter name : ")
|
||||
scanner.Scan()
|
||||
name := scanner.Text()
|
||||
fmt.Print(" Enter value : ")
|
||||
scanner.Scan()
|
||||
value := scanner.Text()
|
||||
check(scanner.Err())
|
||||
ss.runtimeFields[name] = value
|
||||
fmt.Println()
|
||||
}
|
||||
for {
|
||||
fmt.Print("Which field do you want to inspect ? ")
|
||||
scanner.Scan()
|
||||
name := scanner.Text()
|
||||
check(scanner.Err())
|
||||
value, ok := ss.runtimeFields[name]
|
||||
if !ok {
|
||||
fmt.Println("There is no field of that name, try again")
|
||||
} else {
|
||||
fmt.Printf("Its value is '%s'\n", value)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
class A {
|
||||
final x = { it + 25 }
|
||||
private map = new HashMap()
|
||||
Object get(String key) { map[key] }
|
||||
void set(String key, Object value) { map[key] = value }
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
def a = new A()
|
||||
a.y = 55
|
||||
a.z = { println (new Date()); Thread.sleep 5000 }
|
||||
|
||||
println a.x(25)
|
||||
println a.y
|
||||
(0..2).each(a.z)
|
||||
|
||||
println a.q
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
link ximage
|
||||
|
||||
procedure main()
|
||||
c1 := foo(1,2) # instance of foo
|
||||
write("c1:\n",ximage(c1))
|
||||
c1 := extend(c1,["c","d"],[8,9]) # 2 new fields
|
||||
write("new c1:\n",ximage(c1))
|
||||
c1 := extend(c1,["e"],[7]) # 1 more
|
||||
write("newest c1:\n",ximage(c1))
|
||||
end
|
||||
|
||||
class foo(a,b) # dummy class
|
||||
end
|
||||
|
||||
procedure extend(instance,newvars,newvals) #: extend a class instance
|
||||
every put(f := [],fieldnames(instance)) # copy existing fieldnames
|
||||
c := ["tempconstructor"] ||| f # new constructor
|
||||
every put(c,!newvars) # append new vars
|
||||
t := constructor!c # new constructor
|
||||
x := t() # new instance
|
||||
every x[v := !f] := instance[v] # same as old instance
|
||||
x.__s := x # new self
|
||||
if \newvals then
|
||||
every i := 1 to min(*newvars,*newvals) do
|
||||
x[newvars[i]] := newvals[i] # add new vars = values
|
||||
return x
|
||||
end
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
Empty := Object clone
|
||||
|
||||
e := Empty clone
|
||||
e foo := 1
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
C=:<'exampleclass' NB. this will be our class name
|
||||
V__C=: 0 NB. ensure the class exists
|
||||
OBJ1=:conew 'exampleclass' NB. create an instance of our class
|
||||
OBJ2=:conew 'exampleclass' NB. create another instance
|
||||
V__OBJ1,V__OBJ2 NB. both of our instances exist
|
||||
0
|
||||
W__OBJ1 NB. instance does not have a W
|
||||
|value error
|
||||
W__OBJ1=: 0 NB. here, we add a W to this instance
|
||||
W__OBJ1 NB. this instance now has a W
|
||||
0
|
||||
W__OBJ2 NB. our other instance does not
|
||||
|value error
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
e = {} // generic object
|
||||
e.foo = 1
|
||||
e["bar"] = 2 // name specified at runtime
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"a":1} as $a | ($a + {"b":2}) as $a | $a
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
$a|.c = 3
|
||||
# or equivalently:
|
||||
$a|.["c"] = 3
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
{"phoneNumbers": [
|
||||
{
|
||||
"type": "home",
|
||||
"number": "212 555-1234"
|
||||
},
|
||||
{
|
||||
"type": "office",
|
||||
"number": "646 555-4567"
|
||||
},
|
||||
{
|
||||
"type": "mobile",
|
||||
"number": "123 456-7890"
|
||||
}]}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
mutable struct Contact
|
||||
name::String
|
||||
phonenumber::Dict{Any,Any}
|
||||
end
|
||||
|
||||
person = Contact("Jane Doe", Dict())
|
||||
person.phonenumber["home"] = "212 555-1234"
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
// version 1.1.2
|
||||
|
||||
class SomeClass {
|
||||
val runtimeVariables = mutableMapOf<String, Any>()
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val sc = SomeClass()
|
||||
println("Create two variables at runtime: ")
|
||||
for (i in 1..2) {
|
||||
println(" Variable #$i:")
|
||||
print(" Enter name : ")
|
||||
val name = readLine()!!
|
||||
print(" Enter value : ")
|
||||
val value = readLine()!!
|
||||
sc.runtimeVariables.put(name, value)
|
||||
println()
|
||||
}
|
||||
while (true) {
|
||||
print("Which variable do you want to inspect ? ")
|
||||
val name = readLine()!!
|
||||
val value = sc.runtimeVariables[name]
|
||||
if (value == null) {
|
||||
println("There is no variable of that name, try again")
|
||||
} else {
|
||||
println("Its value is '${sc.runtimeVariables[name]}'")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
HAI 1.3
|
||||
|
||||
I HAS A object ITZ A BUKKIT
|
||||
I HAS A name, I HAS A value
|
||||
|
||||
IM IN YR interface
|
||||
VISIBLE "R U WANTIN 2 (A)DD A VAR OR (P)RINT 1? "!
|
||||
I HAS A option, GIMMEH option
|
||||
|
||||
option, WTF?
|
||||
OMG "A"
|
||||
VISIBLE "NAME: "!, GIMMEH name
|
||||
VISIBLE "VALUE: "!, GIMMEH value
|
||||
object HAS A SRS name ITZ value, GTFO
|
||||
OMG "P"
|
||||
VISIBLE "NAME: "!, GIMMEH name
|
||||
VISIBLE object'Z SRS name
|
||||
OIC
|
||||
IM OUTTA YR interface
|
||||
|
||||
KTHXBYE
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
myObject := Object clone.
|
||||
|
||||
;; Name known at compile-time.
|
||||
myObject foo := "bar".
|
||||
|
||||
;; Name known at runtime.
|
||||
myObject slot 'foo = "bar".
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
obj = script("MyClass").new()
|
||||
|
||||
put obj.foo
|
||||
-- "FOO"
|
||||
|
||||
-- add new property 'bar'
|
||||
obj.setProp(#bar, "BAR")
|
||||
put obj.bar
|
||||
-- "BAR"
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
% we start by defining an empty object
|
||||
:- object(foo).
|
||||
|
||||
% ensure that complementing categories are allowed
|
||||
:- set_logtalk_flag(complements, allow).
|
||||
|
||||
:- end_object.
|
||||
|
||||
% define a complementing category, adding a new predicate
|
||||
:- category(bar,
|
||||
complements(foo)).
|
||||
|
||||
:- public(bar/1).
|
||||
bar(1).
|
||||
bar(2).
|
||||
bar(3).
|
||||
|
||||
:- end_category.
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
| ?- foo::bar(X).
|
||||
X = 1 ;
|
||||
X = 2 ;
|
||||
X = 3
|
||||
true
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
empty = {}
|
||||
empty.foo = 1
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
Module checkit {
|
||||
class alfa {
|
||||
x=5
|
||||
}
|
||||
\\ a class is a global function which return a group
|
||||
Dim a(5)=alfa()
|
||||
Print a(3).x=5
|
||||
For a(3) {
|
||||
group anyname { y=10}
|
||||
\\ merge anyname to this (a(3))
|
||||
this=anyname
|
||||
}
|
||||
Print a(3).y=10
|
||||
Print Valid(a(2).y)=false
|
||||
\\ make a copy of a(3) to m
|
||||
m=a(3)
|
||||
m.y*=2
|
||||
Print m.y=20, a(3).y=10
|
||||
\\ make a pointer to a(3) in n
|
||||
n->a(3)
|
||||
Print n=>y=10
|
||||
n=>y+=20
|
||||
Print a(3).y=30
|
||||
\\ now n points to a(2)
|
||||
n->a(2)
|
||||
Print Valid(n=>y)=false ' y not exist in a(2)
|
||||
Print n is a(2) ' true
|
||||
\\ we don't have types for groups
|
||||
Print valid(@n as m)=false ' n haven't all members of m
|
||||
Print valid(@m as n)=true ' m have all members of n
|
||||
}
|
||||
checkit
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
f[a]=1;
|
||||
f[b]=2;
|
||||
f[a]=3;
|
||||
? f
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
empty = {}
|
||||
empty.foo = 1
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
empty = {}
|
||||
varName = "foo"
|
||||
empty[varName] = 1
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
import morfa.base;
|
||||
|
||||
template <T>
|
||||
public struct Dynamic
|
||||
{
|
||||
var data: Dict<text, T>;
|
||||
}
|
||||
|
||||
// convenience to create new Dynamic instances
|
||||
template <T>
|
||||
public property dynamic(): Dynamic<T>
|
||||
{
|
||||
return Dynamic<T>(new Dict<text,T>());
|
||||
}
|
||||
|
||||
// introduce replacement operator for . - a quoting ` operator
|
||||
public operator ` { kind = infix, precedence = max, associativity = left, quoting = right }
|
||||
template <T>
|
||||
public func `(d: Dynamic<T>, name: text): DynamicElementAccess<T>
|
||||
{
|
||||
return DynamicElementAccess<T>(d, name);
|
||||
}
|
||||
|
||||
// to allow implicit cast from the wrapped instance of T (on access)
|
||||
template <T>
|
||||
public func convert(dea: DynamicElementAccess<T>): T
|
||||
{
|
||||
return dea.holder.data[dea.name];
|
||||
}
|
||||
|
||||
// cannot overload assignment - introduce special assignment operator
|
||||
public operator <- { kind = infix, precedence = assign }
|
||||
template <T>
|
||||
public func <-(access: DynamicElementAccess<T>, newEl: T): void
|
||||
{
|
||||
access.holder.data[access.name] = newEl;
|
||||
}
|
||||
|
||||
func main(): void
|
||||
{
|
||||
var test = dynamic<int>;
|
||||
|
||||
test`a <- 10;
|
||||
test`b <- 20;
|
||||
test`a <- 30;
|
||||
|
||||
println(test`a, test`b);
|
||||
}
|
||||
|
||||
// private helper structure
|
||||
template <T>
|
||||
struct DynamicElementAccess
|
||||
{
|
||||
var holder: Dynamic<T>;
|
||||
var name: text;
|
||||
|
||||
import morfa.io.format.Formatter;
|
||||
public func format(formatt: text, formatter: Formatter): text
|
||||
{
|
||||
return getFormatFunction(holder.data[name])(formatt, formatter);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import json
|
||||
{.experimental: "dotOperators".}
|
||||
template `.=`(js: JsonNode, field: untyped, value: untyped) =
|
||||
js[astToStr(field)] = %value
|
||||
template `.`(js: JsonNode, field: untyped): JsonNode = js[astToStr(field)]
|
||||
var obj = newJObject()
|
||||
obj.foo = "bar"
|
||||
echo(obj.foo)
|
||||
obj.key = 3
|
||||
echo(obj.key)
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself
|
||||
|
||||
int main (int argc, const char *argv[]) {
|
||||
@autoreleasepool {
|
||||
|
||||
id e = [[NSObject alloc] init];
|
||||
|
||||
// set
|
||||
objc_setAssociatedObject(e, fooKey, @1, OBJC_ASSOCIATION_RETAIN);
|
||||
|
||||
// get
|
||||
NSNumber *associatedObject = objc_getAssociatedObject(e, fooKey);
|
||||
NSLog(@"associatedObject: %@", associatedObject);
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
int main (int argc, const char *argv[]) {
|
||||
@autoreleasepool {
|
||||
|
||||
id e = [[NSObject alloc] init];
|
||||
|
||||
// set
|
||||
objc_setAssociatedObject(e, @selector(foo), @1, OBJC_ASSOCIATION_RETAIN);
|
||||
|
||||
// get
|
||||
NSNumber *associatedObject = objc_getAssociatedObject(e, @selector(foo));
|
||||
NSLog(@"associatedObject: %@", associatedObject);
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
% Given struct "test"
|
||||
test.b=1;
|
||||
test = setfield (test, "c", 3);
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
d = .dynamicvar~new
|
||||
d~foo = 123
|
||||
say d~foo
|
||||
|
||||
d2 = .dynamicvar2~new
|
||||
d~bar = "Fred"
|
||||
say d~bar
|
||||
|
||||
-- a class that allows dynamic variables. Since this is a mixin, this
|
||||
-- capability can be added to any class using multiple inheritance
|
||||
::class dynamicvar MIXINCLASS object
|
||||
::method init
|
||||
expose variables
|
||||
variables = .directory~new
|
||||
|
||||
-- the UNKNOWN method is invoked for all unknown messages. We turn this
|
||||
-- into either an assignment or a retrieval for the desired item
|
||||
::method unknown
|
||||
expose variables
|
||||
use strict arg messageName, arguments
|
||||
|
||||
-- assignment messages end with '=', which tells us what to do
|
||||
if messageName~right(1) == '=' then do
|
||||
variables[messageName~left(messageName~length - 1)] = arguments[1]
|
||||
end
|
||||
else do
|
||||
return variables[messageName]
|
||||
end
|
||||
|
||||
|
||||
-- this class is not a direct subclass of dynamicvar, but mixes in the
|
||||
-- functionality using multiple inheritance
|
||||
::class dynamicvar2 inherit dynamicvar
|
||||
::method init
|
||||
-- mixin init methods are not automatically invoked, so we must
|
||||
-- explicitly invoke this
|
||||
self~init:.dynamicvar
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
d = .dynamicvar~new
|
||||
d~foo = 123
|
||||
say d~foo
|
||||
|
||||
-- a class that allows dynamic variables. Since this is a mixin, this
|
||||
-- capability can be added to any class using multiple inheritance
|
||||
::class dynamicvar MIXINCLASS object
|
||||
::method init
|
||||
expose variables
|
||||
variables = .directory~new
|
||||
|
||||
-- the unknown method will get invoked any time an unknown method is
|
||||
-- used. This UNKNOWN method will add attribute methods for the given
|
||||
-- name that will be available on all subsequent uses.
|
||||
::method unknown
|
||||
expose variables
|
||||
use strict arg messageName, arguments
|
||||
|
||||
-- check for an assignment or fetch, and get the proper
|
||||
-- method name
|
||||
if messageName~right(1) == '=' then do
|
||||
variableName = messageName~left(messageName~length - 1)
|
||||
end
|
||||
else do
|
||||
variableName = messageName
|
||||
end
|
||||
|
||||
-- define a pair of methods to set and retrieve the instance variable. These are
|
||||
-- created at the object scope
|
||||
self~setMethod(variableName, 'expose' variableName'; return' variableName)
|
||||
self~setMethod(variableName'=', 'expose' variableName'; use strict arg value;' variableName '= value' )
|
||||
|
||||
-- reinvoke the original message. This will now go to the dynamically added
|
||||
methods
|
||||
forward to(self) message(messageName) arguments(arguments)
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
'=================
|
||||
class fleximembers
|
||||
'=================
|
||||
|
||||
indexbase 0
|
||||
bstring buf, *varl
|
||||
sys dp,en
|
||||
|
||||
method addVar(string name,dat)
|
||||
sys le=len buf
|
||||
if dp+16>le then
|
||||
buf+=nuls 0x100 : le+=0x100 :
|
||||
end if
|
||||
@varl=?buf
|
||||
varl[en]=name
|
||||
varl[en+1]=dat
|
||||
dp+=2*sizeof sys
|
||||
en+=2 'next slot
|
||||
end method
|
||||
|
||||
method find(string name) as sys
|
||||
sys i
|
||||
for i=0 to <en step 2
|
||||
if name=varl[i] then return i+1
|
||||
next
|
||||
end method
|
||||
|
||||
method vars(string name) as string
|
||||
sys f=find(name)
|
||||
if f then return varl[f]
|
||||
end method
|
||||
|
||||
method VarF(string name) as double
|
||||
return vars(name)
|
||||
end method
|
||||
|
||||
method VarI(string name) as sys
|
||||
return vars(name)
|
||||
end method
|
||||
|
||||
method vars(string name,dat)
|
||||
bstring varl at buf
|
||||
sys f=find(name)
|
||||
if f then varl[f]=dat
|
||||
end method
|
||||
|
||||
method delete()
|
||||
sys i
|
||||
sys v at buf
|
||||
for i=0 to <en
|
||||
freememory v[i]
|
||||
next
|
||||
freememory ?buf
|
||||
? buf=0 : en=0 : dp=0
|
||||
end method
|
||||
|
||||
end class
|
||||
|
||||
'TEST
|
||||
|
||||
fleximembers a
|
||||
|
||||
a.addVar "p",5
|
||||
a.addVar "q",4.5
|
||||
a.addVar "r","123456"
|
||||
|
||||
print a.Vars("q")+a.vars("q") 'result 4.54.5
|
||||
print a.Varf("q")+a.varf("q") 'result 9
|
||||
|
||||
a.delete
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
declare
|
||||
%% Creates a new class derived from BaseClass
|
||||
%% with an added feature (==public immutable attribute)
|
||||
fun {AddFeature BaseClass FeatureName FeatureValue}
|
||||
class DerivedClass from BaseClass
|
||||
feat
|
||||
%% "FeatureName" is escaped, otherwise a new variable
|
||||
%% refering to a private feature would be created
|
||||
!FeatureName:FeatureValue
|
||||
end
|
||||
in
|
||||
DerivedClass
|
||||
end
|
||||
|
||||
class Base
|
||||
feat
|
||||
bar:1
|
||||
|
||||
meth init
|
||||
skip
|
||||
end
|
||||
end
|
||||
|
||||
Derived = {AddFeature Base foo 2}
|
||||
|
||||
Instance = {New Derived init}
|
||||
in
|
||||
{Show Instance.bar} %% inherited feature
|
||||
{Show Instance.foo} %% feature of "synthesized" class
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
class E {};
|
||||
|
||||
$e=new E();
|
||||
|
||||
$e->foo=1;
|
||||
|
||||
$e->{"foo"} = 1; // using a runtime name
|
||||
$x = "foo";
|
||||
$e->$x = 1; // using a runtime name in a variable
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
unit MyObjDef;
|
||||
{$mode objfpc}{$h+}{$interfaces com}
|
||||
interface
|
||||
|
||||
function MyObjCreate: Variant;
|
||||
|
||||
implementation
|
||||
uses
|
||||
Variants, Generics.Collections;
|
||||
|
||||
var
|
||||
MyObjType: TInvokeableVariantType;
|
||||
|
||||
type
|
||||
IMyObj = interface
|
||||
procedure SetVar(const aName: string; const aValue: Variant);
|
||||
function GetVar(const aName: string): Variant;
|
||||
end;
|
||||
|
||||
TMyObj = class(TInterfacedObject, IMyObj)
|
||||
strict private
|
||||
FMap: specialize TDictionary<string, Variant>;
|
||||
public
|
||||
constructor Create;
|
||||
destructor Destroy; override;
|
||||
procedure SetVar(const aName: string; const aValue: Variant);
|
||||
function GetVar(const aName: string): Variant;
|
||||
end;
|
||||
|
||||
TMyData = packed record
|
||||
VType: TVarType;
|
||||
Dummy1: array[0..5] of Byte;
|
||||
Dummy2: Pointer;
|
||||
FObj: IMyObj;
|
||||
end;
|
||||
|
||||
TMyObjType = class(TInvokeableVariantType)
|
||||
procedure Clear(var V: TVarData); override;
|
||||
procedure Copy(var aDst: TVarData; const aSrc: TVarData; const Indir: Boolean); override;
|
||||
function GetProperty(var aDst: TVarData; const aData: TVarData; const aName: string): Boolean; override;
|
||||
function SetProperty(var V: TVarData; const aName: string; const aData: TVarData): Boolean; override;
|
||||
end;
|
||||
|
||||
function MyObjCreate: Variant;
|
||||
begin
|
||||
VarClear(Result);
|
||||
TMyData(Result).VType := MyObjType.VarType;
|
||||
TMyData(Result).FObj := TMyObj.Create;
|
||||
end;
|
||||
|
||||
constructor TMyObj.Create;
|
||||
begin
|
||||
FMap := specialize TDictionary<string, Variant>.Create;
|
||||
end;
|
||||
|
||||
destructor TMyObj.Destroy;
|
||||
begin
|
||||
FMap.Free;
|
||||
inherited;
|
||||
end;
|
||||
|
||||
procedure TMyObj.SetVar(const aName: string; const aValue: Variant);
|
||||
begin
|
||||
FMap.AddOrSetValue(LowerCase(aName), aValue);
|
||||
end;
|
||||
|
||||
function TMyObj.GetVar(const aName: string): Variant;
|
||||
begin
|
||||
if not FMap.TryGetValue(LowerCase(aName), Result) then Result := Null;
|
||||
end;
|
||||
|
||||
procedure TMyObjType.Clear(var V: TVarData);
|
||||
begin
|
||||
TMyData(V).FObj := nil;
|
||||
V.VType := varEmpty;
|
||||
end;
|
||||
|
||||
procedure TMyObjType.Copy(var aDst: TVarData; const aSrc: TVarData; const Indir: Boolean);
|
||||
begin
|
||||
VarClear(Variant(aDst));
|
||||
TMyData(aDst) := TMyData(aSrc);
|
||||
end;
|
||||
|
||||
function TMyObjType.GetProperty(var aDst: TVarData; const aData: TVarData; const aName: string): Boolean;
|
||||
begin
|
||||
Result := True;
|
||||
Variant(aDst) := TMyData(aData).FObj.GetVar(aName);
|
||||
end;
|
||||
|
||||
function TMyObjType.SetProperty(var V: TVarData; const aName: string; const aData: TVarData): Boolean;
|
||||
begin
|
||||
Result := True;
|
||||
TMyData(V).FObj.SetVar(aName, Variant(aData));
|
||||
end;
|
||||
|
||||
initialization
|
||||
MyObjType := TMyObjType.Create;
|
||||
finalization
|
||||
MyObjType.Free;
|
||||
end.
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
program test;
|
||||
{$mode objfpc}{$h+}
|
||||
uses
|
||||
MyObjDef;
|
||||
|
||||
var
|
||||
MyObj: Variant;
|
||||
|
||||
begin
|
||||
MyObj := MyObjCreate;
|
||||
MyObj.Answer := 42;
|
||||
MyObj.Foo := 'Bar';
|
||||
MyObj.When := TDateTime(34121);
|
||||
WriteLn(MyObj.Answer);
|
||||
WriteLn(MyObj.Foo);
|
||||
//check if variable names are case-insensitive, as it should be in Pascal
|
||||
WriteLn(MyObj.wHen);
|
||||
end.
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package Empty;
|
||||
|
||||
# Constructor. Object is hash.
|
||||
sub new { return bless {}, shift; }
|
||||
|
||||
package main;
|
||||
|
||||
# Object.
|
||||
my $o = Empty->new;
|
||||
|
||||
# Set runtime variable (key => value).
|
||||
$o->{'foo'} = 1;
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
-->
|
||||
<span style="color: #008080;">class</span> <span style="color: #000000;">wobbly</span> <span style="color: #000000;">dynamic</span>
|
||||
<span style="color: #000080;font-style:italic;">-- (pre-define a few fields/methods if you like)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
|
||||
<span style="color: #000000;">wobbly</span> <span style="color: #000000;">wobble</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
|
||||
<span style="color: #0000FF;">?<span style="color: #000000;">wobble<span style="color: #0000FF;">.<span style="color: #000000;">jelly</span> <span style="color: #000080;font-style:italic;">-- 0
|
||||
--?wobble["jelly"] -- for dynamic names use []</span>
|
||||
<span style="color: #000000;">wobble<span style="color: #0000FF;">.<span style="color: #000000;">jelly</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"green"</span>
|
||||
<span style="color: #0000FF;">?<span style="color: #000000;">wobble<span style="color: #0000FF;">.<span style="color: #000000;">jelly</span> <span style="color: #000080;font-style:italic;">-- "green"
|
||||
<!--
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
: (setq MyObject (new '(+MyClass))) # Create some object
|
||||
-> $385605941
|
||||
: (put MyObject 'newvar '(some value)) # Set variable
|
||||
-> (some value)
|
||||
: (show MyObject) # Show the object
|
||||
$385605941 (+MyClass)
|
||||
newvar (some value)
|
||||
-> $385605941
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
class CSV
|
||||
{
|
||||
mapping variables = ([]);
|
||||
|
||||
mixed `->(string name)
|
||||
{
|
||||
return variables[name];
|
||||
}
|
||||
|
||||
void `->=(string name, mixed value)
|
||||
{
|
||||
variables[name] = value;
|
||||
}
|
||||
|
||||
array _indices()
|
||||
{
|
||||
return indices(variables);
|
||||
}
|
||||
}
|
||||
|
||||
object csv = CSV();
|
||||
csv->greeting = "hello world";
|
||||
csv->count = 1;
|
||||
csv->lang = "Pike";
|
||||
|
||||
indices(csv);
|
||||
Result: ({ /* 3 elements */
|
||||
"lang",
|
||||
"count",
|
||||
"greeting"
|
||||
})
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
lib objectclass;
|
||||
|
||||
define :class foo;
|
||||
enddefine;
|
||||
|
||||
define define_named_method(method, class);
|
||||
lvars method_str = method >< '';
|
||||
lvars class_str = class >< '';
|
||||
lvars method_hash_str = 'hash_' >< length(class_str) >< '_'
|
||||
>< class_str >< '_' >< length(method_str)
|
||||
>< '_' >< method_str;
|
||||
lvars method_hash = consword(method_hash_str);
|
||||
pop11_compile([
|
||||
lvars ^method_hash = newassoc([]);
|
||||
define :method ^method(self : ^class);
|
||||
^method_hash(self);
|
||||
enddefine;
|
||||
define :method updaterof ^method(val, self : ^class);
|
||||
val -> ^method_hash(self);
|
||||
enddefine;
|
||||
]);
|
||||
enddefine;
|
||||
|
||||
define_named_method("met1", "foo");
|
||||
lvars bar = consfoo();
|
||||
met1(bar) => ;;; default value -- false
|
||||
"baz" -> met1(bar);
|
||||
met1(bar) => ;;; new value
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
$x = 42 `
|
||||
| Add-Member -PassThru `
|
||||
NoteProperty `
|
||||
Title `
|
||||
"The answer to the question about life, the universe and everything"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
class empty(object):
|
||||
pass
|
||||
e = empty()
|
||||
|
|
@ -0,0 +1 @@
|
|||
e.foo = 1
|
||||
|
|
@ -0,0 +1 @@
|
|||
setattr(e, name, value)
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
class empty(object):
|
||||
def __init__(this):
|
||||
this.foo = "whatever"
|
||||
|
||||
def patch_empty(obj):
|
||||
def fn(self=obj):
|
||||
print self.foo
|
||||
obj.print_output = fn
|
||||
|
||||
e = empty()
|
||||
patch_empty(e)
|
||||
e.print_output()
|
||||
# >>> whatever
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
REBOL [
|
||||
Title: "Add Variables to Class at Runtime"
|
||||
URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime
|
||||
]
|
||||
|
||||
; As I understand it, a REBOL object can only ever have whatever
|
||||
; properties it was born with. However, this is somewhat offset by the
|
||||
; fact that every instance can serve as a prototype for a new object
|
||||
; that also has the new parameter you want to add.
|
||||
|
||||
; Here I create an empty instance of the base object (x), then add the
|
||||
; new instance variable while creating a new object prototyped from
|
||||
; x. I assign the new object to x, et voila', a dynamically added
|
||||
; variable.
|
||||
|
||||
x: make object! [] ; Empty object.
|
||||
|
||||
x: make x [
|
||||
newvar: "forty-two" ; New property.
|
||||
]
|
||||
|
||||
print "Empty object modifed with 'newvar' property:"
|
||||
probe x
|
||||
|
||||
; A slightly more interesting example:
|
||||
|
||||
starfighter: make object! [
|
||||
model: "unknown"
|
||||
pilot: none
|
||||
]
|
||||
x-wing: make starfighter [
|
||||
model: "Incom T-65 X-wing"
|
||||
]
|
||||
|
||||
squadron: reduce [
|
||||
make x-wing [pilot: "Luke Skywalker"]
|
||||
make x-wing [pilot: "Wedge Antilles"]
|
||||
make starfighter [
|
||||
model: "Slayn & Korpil B-wing"
|
||||
pilot: "General Salm"
|
||||
]
|
||||
]
|
||||
|
||||
; Adding new property here.
|
||||
squadron/1: make squadron/1 [deathstar-removal-expert: yes]
|
||||
|
||||
print [crlf "Fighter squadron:"]
|
||||
foreach pilot squadron [probe pilot]
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
class Bar { } # an empty class
|
||||
|
||||
my $object = Bar.new; # new instance
|
||||
|
||||
role a_role { # role to add a variable: foo,
|
||||
has $.foo is rw = 2; # with an initial value of 2
|
||||
}
|
||||
|
||||
$object does a_role; # compose in the role
|
||||
|
||||
say $object.foo; # prints: 2
|
||||
$object.foo = 5; # change the variable
|
||||
say $object.foo; # prints: 5
|
||||
|
||||
my $ohno = Bar.new; # new Bar object
|
||||
#say $ohno.foo; # runtime error, base Bar class doesn't have the variable foo
|
||||
|
||||
my $this = $object.new; # instantiate a new Bar derived from $object
|
||||
say $this.foo; # prints: 2 - original role value
|
||||
|
||||
my $that = $object.clone; # instantiate a new Bar derived from $object copying any variables
|
||||
say $that.foo; # 5 - value from the cloned object
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
my $lue = 42 but role { has $.answer = "Life, the Universe, and Everything" }
|
||||
|
||||
say $lue; # 42
|
||||
say $lue.answer; # Life, the Universe, and Everything
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
use MONKEY-TYPING;
|
||||
augment class Int {
|
||||
method answer { "Life, the Universe, and Everything" }
|
||||
}
|
||||
say 42.answer; # Life, the Universe, and Everything
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
person: make object! [
|
||||
name: none
|
||||
age: none
|
||||
]
|
||||
|
||||
people: reduce [make person [name: "fred" age: 20] make person [name: "paul" age: 21]]
|
||||
people/1: make people/1 [skill: "fishing"]
|
||||
|
||||
foreach person people [
|
||||
print reduce [person/age "year old" person/name "is good at" any [select person 'skill "nothing"]]
|
||||
]
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
o1 = new point
|
||||
addattribute(o1,"x")
|
||||
addattribute(o1,"y")
|
||||
addattribute(o1,"z")
|
||||
see o1 {x=10 y=20 z=30}
|
||||
class point
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
class Empty
|
||||
end
|
||||
|
||||
e = Empty.new
|
||||
class << e
|
||||
attr_accessor :foo
|
||||
end
|
||||
e.foo = 1
|
||||
puts e.foo # output: "1"
|
||||
|
||||
f = Empty.new
|
||||
f.foo = 1 # raises NoMethodError
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
yes_no = "Yes"
|
||||
|
||||
def yes_no.not
|
||||
replace( self=="Yes" ? "No": "Yes")
|
||||
end
|
||||
|
||||
#Demo:
|
||||
p yes_no.not # => "No"
|
||||
p yes_no.not # => "Yes"
|
||||
p "aaa".not # => undefined method `not' for "aaa":String (NoMethodError)
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import language.dynamics
|
||||
import scala.collection.mutable.HashMap
|
||||
|
||||
class A extends Dynamic {
|
||||
private val map = new HashMap[String, Any]
|
||||
def selectDynamic(name: String): Any = {
|
||||
return map(name)
|
||||
}
|
||||
def updateDynamic(name:String)(value: Any) = {
|
||||
map(name) = value
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
scala> val a = new A
|
||||
a: A = A@7b20f29d
|
||||
|
||||
scala> a.foo = 42
|
||||
a.foo: Any = 42
|
||||
|
||||
scala> a.foo
|
||||
res10: Any = 42
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
class Empty{};
|
||||
var e = Empty(); # create a new class instance
|
||||
e{:foo} = 42; # add variable 'foo'
|
||||
say e{:foo}; # print the value of 'foo'
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
define: #Empty -> Cloneable clone.
|
||||
define: #e -> Empty clone.
|
||||
e addSlotNamed: #foo valued: 1.
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
|addSlot p|
|
||||
|
||||
addSlot :=
|
||||
[:obj :slotName |
|
||||
|anonCls newObj|
|
||||
anonCls := obj class
|
||||
subclass:(obj class name,'+') asSymbol
|
||||
instanceVariableNames:slotName
|
||||
classVariableNames:''
|
||||
poolDictionaries:'' category:nil
|
||||
inEnvironment:nil.
|
||||
anonCls compile:('%1 ^ %1' bindWith:slotName).
|
||||
anonCls compile:('%1:v %1 := v' bindWith:slotName).
|
||||
newObj := anonCls cloneFrom:obj.
|
||||
obj become:newObj.
|
||||
].
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
p := Point x:10 y:20.
|
||||
addSlot value:p value:'z'.
|
||||
p z:30.
|
||||
p z.
|
||||
p z:40.
|
||||
p inspect
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
!Object methodsFor:'adding slots'!
|
||||
|
||||
addSlot: slotName
|
||||
|anonCls newObj|
|
||||
|
||||
anonCls := self class
|
||||
subclass:(self class name,'+') asSymbol
|
||||
instanceVariableNames:slotName
|
||||
classVariableNames:''
|
||||
poolDictionaries:'' category:nil
|
||||
inEnvironment:nil.
|
||||
anonCls compile:('%1 ^ %1' bindWith:slotName).
|
||||
anonCls compile:('%1:v %1 := v' bindWith:slotName).
|
||||
newObj := anonCls cloneFrom:self.
|
||||
self become:newObj.
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
p := Point x:10 y:20.
|
||||
p addSlot:'z'. "instance specific added slot"
|
||||
p z:30.
|
||||
p z.
|
||||
p z:40.
|
||||
p inspect. "shows 3 slots"
|
||||
"Point class is unaffected:"
|
||||
p2 := Point x:20 y:30.
|
||||
p2 z:40. -> error; Point does not implement z:
|
||||
p2 inspect. "shows 2 slots"
|
||||
"but we can create another instance of the enhanced point (even though its an anon class)"
|
||||
p3 := p class new.
|
||||
p3 x:1 y:2.
|
||||
p3 z:4.
|
||||
p3 inspect. "shows 3 slots"
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
Object subclass: #Monkey
|
||||
instanceVariableNames: 'aVar'
|
||||
classVariableNames: ''
|
||||
poolDictionaries: ''
|
||||
category: nil !
|
||||
|
||||
!Monkey class methodsFor: 'new instance'!
|
||||
new
|
||||
| o |
|
||||
o := super new.
|
||||
o init.
|
||||
^o
|
||||
!!
|
||||
|
||||
!Monkey methodsFor: 'init instance'!
|
||||
init
|
||||
aVar := 0
|
||||
!
|
||||
initWith: value
|
||||
aVar := value
|
||||
!!
|
||||
|
||||
!Monkey methodsFor: 'set/get the inst var(s)'!
|
||||
setVar: var
|
||||
aVar := var
|
||||
!
|
||||
getVar
|
||||
^aVar
|
||||
!!
|
||||
|
||||
|
||||
"Create a new instance"
|
||||
Smalltalk at: #aMonkey put: (Monkey new) !
|
||||
|
||||
"set the 'original' instance var to 12"
|
||||
aMonkey setVar: 12 .
|
||||
|
||||
"let's see what's inside"
|
||||
aMonkey inspect .
|
||||
|
||||
"add a new instance var"
|
||||
Monkey addInstVarName: 'x'.
|
||||
|
||||
"let's see what's inside now"
|
||||
aMonkey inspect .
|
||||
|
||||
"let us create a new method for x"
|
||||
!Monkey methodsFor: 'about x'!
|
||||
setX: val
|
||||
x := val
|
||||
!
|
||||
x
|
||||
^x
|
||||
!!
|
||||
|
||||
aMonkey setX: 10 .
|
||||
aMonkey inspect .
|
||||
(aMonkey x) printNl .
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import Foundation
|
||||
|
||||
let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)
|
||||
|
||||
class MyClass { }
|
||||
let e = MyClass()
|
||||
|
||||
// set
|
||||
objc_setAssociatedObject(e, fooKey, 1, .OBJC_ASSOCIATION_RETAIN)
|
||||
|
||||
// get
|
||||
if let associatedObject = objc_getAssociatedObject(e, fooKey) {
|
||||
print("associated object: \(associatedObject)")
|
||||
} else {
|
||||
print("no associated object")
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
% package require TclOO
|
||||
% oo::class create summation {
|
||||
constructor {} {
|
||||
variable v 0
|
||||
}
|
||||
method add x {
|
||||
variable v
|
||||
incr v $x
|
||||
}
|
||||
method value {{var v}} {
|
||||
variable $var
|
||||
return [set $var]
|
||||
}
|
||||
destructor {
|
||||
variable v
|
||||
puts "Ended with value $v"
|
||||
}
|
||||
}
|
||||
::summation
|
||||
% set s [summation new]
|
||||
% # Do the monkey patch!
|
||||
% set [info object namespace $s]::time now
|
||||
now
|
||||
% # Prove it's really part of the object...
|
||||
% $s value time
|
||||
now
|
||||
%
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
% oo::class create summation {
|
||||
constructor {} {
|
||||
variable v 0
|
||||
}
|
||||
method add x {
|
||||
variable v
|
||||
incr v $x
|
||||
}
|
||||
method value {{var v}} {
|
||||
variable $var
|
||||
return [set $var]
|
||||
}
|
||||
destructor {
|
||||
variable v
|
||||
puts "Ended with value $v"
|
||||
}
|
||||
}
|
||||
::summation
|
||||
% set s [summation new]
|
||||
% set s2 [summation new]
|
||||
% oo::objdefine $s export varname
|
||||
% # Do the monkey patch...
|
||||
% set [$s varname time] "now"
|
||||
% $s value time
|
||||
now
|
||||
% # Show that it is only in one object...
|
||||
% $s2 value time
|
||||
can't read "time": no such variable
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import "io" for Stdin, Stdout
|
||||
|
||||
class Birds {
|
||||
construct new(userFields) {
|
||||
_userFields = userFields
|
||||
}
|
||||
userFields { _userFields }
|
||||
}
|
||||
|
||||
var userFields = {}
|
||||
System.print("Enter three fields to add to the Birds class:")
|
||||
for (i in 0..2) {
|
||||
System.write("\n name : ")
|
||||
Stdout.flush()
|
||||
var name = Stdin.readLine()
|
||||
System.write(" value: ")
|
||||
Stdout.flush()
|
||||
var value = Num.fromString(Stdin.readLine())
|
||||
userFields[name] = value
|
||||
}
|
||||
|
||||
var birds = Birds.new(userFields)
|
||||
|
||||
System.print("\nYour fields are:\n")
|
||||
for (kv in birds.userFields) {
|
||||
System.print(" %(kv.key) = %(kv.value)")
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
set Object = {}
|
||||
Object.Hello = "World";
|
||||
log(Object.Hello);
|
||||
Loading…
Add table
Add a link
Reference in a new issue