Probably the simplest examples of metaprogramming, quines are curious little programs that write themselves. Some people go to great lengths to write the smallest possible quine for a certain language. I say for a certain language because the difficulty in writing a small quine is dominated by the languages facilities for doing so. For example, in the original BASIC, it's almost trivial:
1. LIST
because the language includes a construct that does exactly what we want. Ive taken a few minutes to write a relatively simple quine in php, here it is:
<?php
$string = '<?php
$string = \'@\';
echo substr_replace($string, addslashes($string), strpos($string, chr(64)), 1);';
echo substr_replace($string, addslashes($string), strpos($string, chr(64)), 1);
If you're wondering, 64 is the ascii code for the @ character above. Im sure you can do it in much less space, but the strategy is the same. The program code must contain a string representation of itself, and at some point you have to do some substitution and some quoting to achieve duplication and correct printing of quote literals ('). As i said before, it's as hard as the language makes it, and php makes it easy with built-in functions like addslashes, strpos and substr_replace.
Quines are not very representantive of metaprogramming, because theyre little more than curious toys. However, I will probably write more on metaprogramming and related concepts (self reference, reflectivity) as they are an important topic in artificial intelligence.
Sources: wikipedia, wikiwikiweb
Suscribirse a:
Enviar comentarios (Atom)
No hay comentarios:
Publicar un comentario