From: | Geoff Wozniak <geoff@wozniak.ca> |
Newsgroups: | comp.compilers |
Date: | 8 Oct 2003 22:23:56 -0400 |
Organization: | WorldCom Canada Ltd. News Reader Service |
References: | 03-10-004 |
Keywords: | design |
Posted-Date: | 08 Oct 2003 22:23:55 EDT |
"Gabriele Farina" <mrfaro@libero.it> writes:
> This little piece of code is useless, I know, but I write it to make you
> understand what I'd like to do. test = class() defines a new class,
> where, dynamically, I add a new method looking at a variable value given
> as input. As you can see I add new method at runtime.
>
> Do you think this can be useful and can be implemented??
>
Aldor (http://www.aldor.org) treats types as first-class values and allows
them to be created and extended at runtime. Here's a simple example:
#include "aldor"
#include "aldorio"
-- Categories are analogous to interfaces in Java
define CatFoo: Category == with {
foo : () -> ();
}
define CatBar: Category == with {
bar : () -> ();
}
-- This defines a domain, which is analogous to a class. "DomFoo"
-- is declared to satisfy the CatFoo category (interface).
DomFoo: CatFoo == add {
foo () : () == ();
}
-- This function takes a type that satisfies the CatFoo category and
-- returns a type that satisfies the CatBar category. The domain is
-- extended using the extend keyword.
myfunc (D: CatFoo): CatBar == {
extend D: CatBar == add {
bar () : () == {
stdout << "Hello, world!" << newline;
}
}
D;
}
define Dprime == myfunc (DomFoo);
-- Bring the exports from Dprime into scope
import from Dprime;
bar ();
N.B. More often than not, in Aldor, you do not have a function extend
a type and return it. You normally just extend a type in the scope as
needed. This code will generate compiler warnings for reasons I won't
get into.
While this specific example is silly, extending types can be very
useful since it allows you to "tweak" things. For example, say you
have a category (interface) that the type Float almost satisfies. You
can extend Float and add this operation to it so that it satifies the
given category *without* defining something like MyFloat (which could,
for all intents and purposes, be used in place of Float and not break
anything). It's used a fair bit in computer algebra, so it's your
call whether or not something like this is useful :)
> There could be any problems??
Yes. It can be very slow if you're not careful and if you don't have
strong type checking, you could have a lot of runtime exceptions.
--
Geoffrey Wozniak
http://wozniak.ca/
Return to the
comp.compilers page.
Search the
comp.compilers archives again.