19 April 2009

Will C++0x benefit Squared?

While developing Squared, I came across the problem of having to execute the code in 2 dimensions: the C++ code and my language code. This because the Squared Library is a C++ Library and is meant to be executed in C++ programs as well.

An example will clarify:

class Object { ... }; // Base object
class List: public Object { list <Object*> objs_; };

The whole library is based on Object. So containers (like List) are Objects themselves. Clear enough. Now: the List object should have a method for appending an object, say "append", which can be used from the language (i.e. a dynamic method for executing a method giving a name).

list->send("append", someObject);

The problem with it is that it's sooo slow to execute, and absolutely doesn't fit a library. If you're using a C++ library, you expect to append an object like this:

list->append(someObject);

Here's the two level: the same code (append), must be present both registered as "append" message AND append() method. To implement this effectively in C++ is quite a pain. Why? Let's see.

Is it clear that you'll need to have a append() method in List class, as usual C++:

class List {
...
void append(Object *o) { objs_.append(o); }
};


But also, we need to have a "append" message registered somewhere; messages are dispatched by methods objects, that is an Object that's like:

class Append_message: public Object {
Object *execute(Object *caller, list<Object> parameters) {
List *l = dynamic_cast<List<(caller);
// Error checking
l->append(parameters.first);
return caller;
}
};


This because, being the whole library composed by Objects, code must be an Object too. This class will be instantiated and the instance will be called "append" and registered in the List objects and finally used by the language.

Now: is it evident how much this code is "just a mapping". But there are some questions:
First, where's Append_message defined? Since it's an append()-related thing, it would be nice to be defined together with append().
Second, is there a way to define every XYZ_message in an automated way? Are they "just mapping function objects"?

The second question is, in some ways, related to the first: what if methods and message should behave differently? It would be nice to have in the same place the specifications of these behaviors.

So I tired to answer the first question with functors - this would solve the second question too: "let the implementor decide if they're just mapping or not".
This is what I aimed to do (pseudo-C++, but gives the idea).

class Append: public Object {
void operator()(Object *o) {
objs_->append(o);
}
Object *exec(Object *caller, list<Object*> params) {
List l = /* convert the caller */;
l->append(params.first);
return caller;
}
};

cass List: public Object {
list<Object *> objs_;
public:
Append append("append");
};

list->append(o);
list->send("append", o);


Got the idea? Define a function and the mapping with the language in the same place, possibly in a functor (it can be reused in different objects).
Probably you noticed it immediately: objs_ isn't defined in Append classes! The code can't reach it, since it's private to the Append class. A solution would be to make the Append friend, or just to have a public obj_.
Friends aren't always a good thing and public members are against information hiding - they're really bad.

Multiple inheritance won't help because a base class can't refer to a member of a derived class - and of course naming collisions may be disturbing.

I would like to add something to the answer to the second question: is it possible to build a default mapping pattern? Something like "method-to-functor".
The problem of having such a technique is correlated in having a types-mapping system: when you define a method for your C++ class, it's in the form

RetType Name(ParameterList)

And you need to map it to:

Object *exec(Object *caller, list<Object*> params)

So one need a system to map:

1. "Object *caller" to an object of your type (e.g. List *). This is straightforward, as it's always a dynamic_cast<Target *>(caller).

2. Each parameter to an object of the relative type. For example, if a function take an int, it should be converted to an Integer object. Of course, Objects don't need any conversion.

3. The return value, same as above.

The problem is that constness, references, pointers and such types have a semantic, and the mapping should consider this semantic.
In addition, there's no guarantee on how many parameters a method has.

Well, I never tried C++0x (err, of course :D I couldn't try it... But >=gcc-4.3 does implement some features of the language) so I still didn't tried to do it in code, but I think that templates will be boosted enough to help me in this case.
In particular, variadic templates may be useful.

I hope to be able to do some template metaprogramming that does the job. I'm still learning it, but I've some ideas that may be useful if combined with variadic templates... In particular, templates manifest kind of "duck typing" features that can be essential in this approach.

My idea is to be able to do what I meant with something like:

typedef BaseList<Append, And, Every, Other, Method, Here> List;

And just use the template system to do what I needed. Maybe it isn't possible. I'll write more later, whenever I find something useful.

Btw, how to resolve the naming issue? Every method must have a name!

typedef BaseList<Append, "append", And, "and", ...> List?

(I think string literals aren't usable in templates. So this method is excluded).

or

class Append { string name; /* = "append" */ ... };

?

Stay --sync

18 April 2009

Il congiuntivo non s'e' perso.

Tanta gente... No, scusate: troppo poca gente a volte si lamenta, perche' i giovani hanno "perso il congiuntivo". E' una realta' qui da noi (zona Milano): davvero in pochi usano il congiuntivo.
Io spesso faccio frasi senza usarlo e penso "avrei dovuto dire...".

Due minuti fa, pero', mi son reso conto che la connotazione data alle parole ha un peso cosi' influente che usare "l'italiano corretto" cambierebbe il significato.

Ecco la situazione d'esempio: una conoscente dice la frase
C: "Per fare la fotomodella mi manca qualche centimetro"

E io rispondo:
A: "Se ti manca solo qualche centimetro, allora sei a buon punto!"

Io, la frase di B la interpreto come: "poiche' le fotomodelle devono essere belle e in forma, oltre che alte, se ti manca solo l'altezza vuol dire che hai gia' tutte le altre qualita'" (i.e. sei bella, ma bassa).

Secondo la mia idea di "Italiano Corretto", avrei dovuto dire:
A: "Se ti mancasse solo qualche centrimetro, allora saresti a buon punto!"

Che interpreto come: "a te manca molto piu' di qualche centimetro per essere una fotomodella" (i.e. sei un cesso, e anche basso).

Ora: che la mia padronanza dell'italiano fosse inesistente, si sapeva :)
Ma... Non sembra un caso strano anche a voi? La prima forma sarebbe stata corretta in Italiano?

Grandi pensieri dell'una e mezza di notte :D
La Cookie Beer non e' affatto male.

Stay --sync

17 April 2009

Pensieri spreconi.

Pensieri veloci sulle recenti parole del nostro caro premier Silvio Berlusconi.
In sostanza ha detto che la Lega Nord avrebbe fatto cadere il governo se si fossero accorpate le elezioni e il referendum.

Com'e' noto (anche se non molto sottolineato), l'accorpamento avrebbe portato ad un guadagno di svariate centinaia di milioni di euro (mi dicono circa 400 Mil. di euri sonanti).

Mio padre ha detto:
"E' furbo: cosi' da la colpa alla Lega Nord e lui fa comunque la faccia di quello che ci ha provato".

Puo' essere... Anzi, e' probabile.

Ma al di la di questa insinuazione (che reputo comunque altamente probabile), ecco qualche approccio piu' logico al problema - scaturito sta volta da me.

0. (premessa) Siamo in periodo di crisi, in Abruzzo c'e' stata una catastrofe naturale e molti, molti soldi dovrebbero essere spesi a sistemare. Il sistema scolastico italiano, come quello sanitario e giudiziario, sono in carenza di fondi.

1. Vista la premessa, direi che anche se si fossero risparmiati 100 euro, sarebbe stato comunque un guadagno. Invece si sprecheranno centinaia di milioni di euro.

2. Se Berlusconi fosse stato onesto e veramente convinto di fare il bene del paese, avrebbe ignorato le minacce e avrebbe fatto il Bene Del Paese. Invece ha scelto di aver paura dei suoi stessi alleati e ha ceduto.

3. Se ha dovuto cedere alle minacce, vuol dire che Berlusconi non ha piu' potere sulla sua coalizione. Sempre ammettendo che abbia agito nel bene della comunita' - cosa improbabile, dato il punto 2.

4. Deduco, visti i fatti e la sua posizione, che Berlusconi ha TUTTI i torti, perche' se fosse stato in buona fede (sia con o senza coraggio) avrebbe agito diversamente da come ha fatto.

Stay --sync

10 April 2009

if...else

I just got an "idea" (i.e. I never heard or read something about it, but perhaps it isn't something new), about the semantic of if-else block.

It's common practice to omit the else part in case it is not necessary:
fun(x) {
if (x == 0)
return 42;
return 42 + fun(x - 1);
}
And sometimes it just happen to need to check for a value and take the adequate countermeasures:
main() {
int v;
input(&v);
if (v <, 0)
v = abs(v);
fun(v);
}

Now, I just noted that semantics in these cases is different, but the use of the if-else block is the same (wrong). Why?
Because in the former case we have a option, like: "if the value is X, then do A, if it isn't do B". In the latter, we have "if value is Y, do an extra C".

The problem is that in the first case we don't use the else, but it's semantically wrong. Using only the if, means "doing something extra in the case, then returning to the normal flow", using the else, means that cases are two, and in both cases we shall do something, so "the normal flow" is to execute one.

So, omitting the else is semantically wrong in the first case.

Stay --sync

SaNiTa' MeNTaLe

Hey, la vedete? E' la! Su su! In alto le teste!
Guarda verso la luna... Eccola! La vedete?

E' la mia sanita' mentale che se n'e' andata.

Stay --sync

08 April 2009

Allocazione di risorse

Questo e' un post promemoria: devo parlarvi di due cose interessanti (o almeno, del mio punto di vista a proposito). Non lo faccio come bozza privata perche' poi mi dimentico, e pubblicarlo mi sprona a completarlo :D

Dio e' un matematico? Perche' la matematica "si infila cosi' bene" nel mondo reale? La matematica "esiste" anche senza ragione? Insomma, hanno ragione i platonici?
In realta' ho gia' un bel pensiero a proposito, ma prima finisco il libro e poi vi faccio sapere.

Altra questione filosofica... L'ho dimenticata. Se mi viene in mente la segno XD

Ohoho e poi mi gaso ancora un po' per il recente successo nell'esame di C++ :D Cioe' non avrei accettato comunque qualsiasi voto minore di 30, ma e' comunque bello sentirsi dire:
Il suo progetto rasenta la perfezione. Ma deve spiegarmi una cosa... E qui si decide il voto: o e' 0 o e' 35.

Sono uscito contento dall'aula :D

Stay --sync

03 April 2009

A.A.A. Cercasi soluzione esponenziale.

Sono le... Uhm, e' piu' tardi di quanto pensassi: 5.12.

Visto che non ho molto tempo, qualche anima di buona volonta' mi realizza/trova/trascrive/copia dal suo libro di algoritmi/ricerca operativa un codice **funzionante** per la risoluzione di un TSP in tempo esponenziale?

Io sotto mano non ne ho e su internet non ne ho trovati senza dover andare a spiluccare applicazioni gia' fatte.

Insomma cerco la soluzione ottima, non quella approssimata...

... Voglio vedere di quanto sbaglia il mio algoritmo :P Ad occhio e croce sembra funzionare abbastanza bene. Molto piu' di quelli genetici che ho visto fin ora o di quelli U'ristici.

Si bhe, anche questo e' U'ristico, ma non l'avevo ancora visto applicato.

Per ora, su 10 risoluzioni circa c'e' stato solo 1 problema evidentemente sbagliato (dove "evidentemente" vuol dire: "io col mio cervello penso che l'altra soluzione sia meno dispendiosa")... Ma devo ancora ritoccare il funzionamento.

Ah, e mi pare OVVIO che non ho assolutamente voglia di scriverlo da me :D
E' noioso fare qualcosa che ha gia' fatto qualcun'altro ;)

Grazie in anticipo...

Buona nott... Buon giorno!!

Stay --sync

01 April 2009

Pesce o panda?

Ahahahaha posso dirlo? :D GOOGLE VAFFANCULOOOO!!! XD

Sta mattina mi chiedevo: "chissa' dov'e' il pesce d'aprile di quest'anno..." E invece non avendo trovato nulla in giro nulla me ne son dimenticato.

Poi apro un PDF con Google Docs (<3) e mi informa che ci sono nuove features.
Non le cago troppo e leggo il PDF.

Poi le guardo meglio, e trovo questa (circa): "Con CADIE puoi inserire messaggi subliminali nelle tue presentazioni".

COOOOOOOOOOOOOOOO_OOOOSA?? Google ha inventato qualche sorta di analizzatore semantico del testo?? Google? O erano esterni??

Mi informo meglio.

Ogni volta che mi fanno questi scherzi io ci credo... Ero li che leggevo, e mentre parlava dei filosofi pensavo "Google ce l'ha fatta", "Ora non mi resta un cazzo da fare", "Un team di ingegneri L'HA FATTO prima di me"... Giuro, me la son bevuta finche' non sono arrivato qui:
In fact, during the first morning of testing she pointed out several important theoretical flaws in particle physics and cosmology.

Poi un flash, una risata e una verifica:
The CADIE Team
March 31st, 2009
11:59pm

:D

Ora continuo a leggerlo giusto per rendere onore a chi mi ha ingannato anche sta volta :)

Stay --sync