PDA

View Full Version : Polyglot!


Strike
09-24-2002, 04:01 PM
Now there are plenty of competitions still to be finished for you all, but if you want another one to choose from, here you have it.

Write a polyglot program.

For those of you who don't know what that means, it means that the same code does the same stuff in two (or more) different programming languages. The trick is to find two programming languages with similar syntax (though I'd say using two dialects of the same language is pretty much cheating, personally). For some inspiration here is a link to some examples: http://www.nyx.net/~gthompso/poly/polyglot.htm

The most "poly" of those polyglots is one that does "Hello world" in 7 languages.

NOTE: this is a hard challenge, and I don't really expect many (if any) responses, so feel free to discuss your thought processes/approaches here if you like. Coming up with a new polyglot program that isn't a mere derivative of existing ones is kind of a feat in and of itself.

Strike
09-24-2002, 04:17 PM
Okay, I did a really really trivial one (which is mostly a copy of the C/Perl polyglot at the top of that list, but with a few tricks. Here it is:


#define foo main() {
#define bar }
#define print(x) printf(x);
#define baz /*
foo = 1
bar = 1
# */

foo
print("Hello world!\n")
bar


Obviously, C preprocessor tricks are nice since they are comments in most scripting/interpreted languages. I also took advantage of the C multiline comment structure so that I could have two lines that would be seen by the Python interpreter (defining variables so that I didn't get NameErrors from them not being defined), but that would not be seen by the C compiler (if we redefined foo and bar, we couldn't get the "main() { }" in there). Lastly, I actually made a C preprocessor macro to turn the Python print function into the C printf function, semicolon and all.

Strike
09-24-2002, 04:19 PM
Duh, I just realized that it could be done much more simply like so:


#define print(x) main() { printf(x); }
print("Hello world!\n")

inkedmn
09-24-2002, 04:20 PM
/me is impressed...

Bradmont
09-24-2002, 08:39 PM
I did one with mips assembly and c++. I was pretty cheap with comments and compiler directives though. It inputs two ints, adds them, then prints the result.


#define mips ASM and C++ Polyglot
#define takes two int inputs and adds them
#include <iostream.h>
#define main ;int main() { 0? 3
#define program }
#define trap 1;cin >> x >> y ; z=
#define End ;cout << x+y << endl;
#define j int x, z,
#define jal ;
#define aaa ;
# /*
.globl x
.globl y
.globl main
# */
j y

main: trap 5
jal aaa
# /*
aaa: add $1, $2, $0 # Place value of $2 in $1
y: trap 5 # Read initial value of $3
x: add $3, $2, $0 # Place value in $3
add $4, $1, $3 # calculate
trap 1 # Display result (in $4)
addi $4, $0, 10 #
trap 101 # Print a newline
trap 10 # "*/End program

Strike
09-24-2002, 08:52 PM
Also, my shorter version (and probably the longer) work fine in Perl too :P