Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

The determined Real Programmer can write Fortran programs in any language.

from Real Programmers Don't Use Pascal

Your task is to write program in your programming language of choice, but you are allowed to use only another language. That is, throw away all coding conventions from one language and replace them with coding conventions from other language. The more the better. Make your program look as if it was written in another language.

For example, Python fan who hates Java could write following Python program in Java:

void my_function()                                                             {
    int i = 9                                                                  ;
    while(i>0)                                                                 {
        System.out.println("Hello!")                                           ;
        i = i - 1                                                              ;}}

Pascal enthusiast forced to use C could write this:

#define begin {
#define end }
#define then
#define writeln(str) puts(str)

if (i == 10) then
begin
    writeln("I hate C");
end

You have to write complete program. The program desn't have to do anything useful.

Good Luck. This is a popularity contest so the code with the most votes wins!

share|improve this question
2  
I am a Python fan who hates Java lol –  Nacib Neme 2 days ago
    
This is great! :) Can anyone figure out how to write a C, C#, Java, JavaScript, PHP etc program in CoffeeScript? I just can't figure out a way to fill the {...} blocks with statements without CS complaining because it expects an object description. –  m.buettner 2 days ago
1  
@m.buettner create your file with the extension .litcoffee. It might help. –  Ismael Miguel 2 days ago
    
@IsmaelMiguel haha, that's clever. My idea was to define functions and variables in such a way that int main(int argc, char **argv) {} is actually valid CoffeeScript, but I failed at putting anything sensible into the braces. –  m.buettner 2 days ago
6  
I don't think you (or the majority of the answers) understand the point of the quote. It's not that a Real Programmer writes code that looks lexically like Fortran even though he's writing in Pascal or LISP: it's that he applies a Fortran way of thinking even when writing in Pascal or LISP; e.g. "As all Real Programmers know, the only useful data structure is the Array.". Great answers would be procedural code in Prolog, functional code in C, object-oriented code in Pascal. –  Peter Taylor yesterday
show 7 more comments

24 Answers

JavaScript in C

I like JavaScript, and I like C. Surely mixing the two would create the best language in the world!!11elevenone

#include <stdio.h>
#define function int
#define var int
struct { int (*log)(const char *,...); } console = { printf };

/* From here on only JavaScript! */

function fac(x){
    if(x < 2) return 1;
    return x * fac(x - 1);
}

function main(){
    console.log("Hello world!\n");

    for(var i = 0; i < 10; i++){
        console.log("%i! = %i\n", i, fac(i));
    }

    return 0;
}

// *Should* we export the main function of this library??/
exports.main = main;

Nope, that's revolting. Ah well... Using a format-string for console.log isn't very JavaScript-y, but it does work (at least in Chrome's developer console).

share|improve this answer
    
+1 ... Except if this was proper JavaScript you would have to call that main somehow ;) –  m.buettner 2 days ago
2  
@m.buettner True, added a dirty hack to pretend we're exporting the main function, like one would do in Node.js libraries. –  Kninnug 2 days ago
1  
Well, the actual trick is the trigraph. You might as well just do main(); in that last line, so you don't need any Node.js assumption. ;) Anyway, I'd +1 again if I could. –  m.buettner 2 days ago
    
+1 for the "!!elevenone" joke... –  itsjeyd yesterday
add comment

I think the brilliant Lennart Augustssen has already won this twice.

First, here's an example of his "weekend hack" implementation of BASIC as a Haskell Monadic DSL, from 2009:

import BASIC

main = runBASIC' $ do

    10 LET I =: 1
    20 LET S =: 0
    30 LET S =: S + 1/I
    40 LET I =: I + 1
    50 IF I <> 100000000 THEN 30
    60 PRINT "Almost infinity is"
    70 PRINT S
    80 END

It works by overloading the number type. The line numbers are really functions that accept arguments. The rest of the line is arguments to the function. The function returns a representation of the Abstract Syntax Tree for the BASIC interpreter to go to work on.

I also recommend you check out Augustssen's entry to the 2006 International Obfuscated C Contest, in which he managed to squeeze into 4k:

  • A bytecode interpreter, written in a subset of C (which he calls Obfuscated C).
  • An Obfuscated C -> bytecode compiler, written in bytecode.

They can share the same file because the byetecode is placed inside C comments.

It's a few years since I followed Augustssen's work, so there may well be other brilliant things he's come up with since then....

share|improve this answer
add comment

C in C++

#include <stdio.h>

int main(int argc, char** argv)
{
        printf("Hello world!\n");
        return 0;
}
share|improve this answer
7  
I see what you did there;) –  el.pescado yesterday
4  
Well, that's a cheap trick, seeing as C++ is 'backwards compatible' with C. –  Nigel Nquande yesterday
    
They're still two different languages, so it's a perfectly valid answer. –  Alex M. yesterday
    
Might as well wedge in Objective C in there if you can too! (I've never programmed in it, but I think it is backward compatible?) –  Thomas Eding 23 hours ago
2  
@AlexM. I think it would be more in the spirit of the question if this was a longer (procedural) example which would clearly benefit from using some classes and which uses other C idioms where some STL goodness would be much more reasonable (say char* instead of std::string). –  m.buettner 13 hours ago
show 3 more comments

PHP and Javascript

This is a polyglot:

You can run this code in both languages:

if("\0"=='\0')
{
    function printf(){
        $b=Array();
        $a=$b['slice']['call'](arguments);
        $a=$a['join']('');
        console.log($a);
        return $a.length;
    };

    function strtoupper($s){return $s['toUpperCase']();}

    function count($a){return $a['length'];}
}

printf('this is cool!');

$c=Array('a','b','c','d');

for($i=0,$l=count($c);$i<$l;++$i)printf("\n",strtoupper($c[$i]));

The trick here is that Javascript uses escape sequences in strings starting with ' and ".
On the other hand, PHP only uses escape sequences in strings starting with " and <<<.

Then, we declare the function printf, which is similar to print but outputs a formated string in PHP.

PHP requires that vars start with $, while Javascript simply allows.

share|improve this answer
add comment

Brainfuck in JavaScript

Javascript is a difficult language ! Let us use Brainfuck, a more understandable language :o)

eval(

//write your easy code below

"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

//end of easy code

.replace(/\]/g,'}')
.replace(/\[/g,'while(a[i]){')
.replace(/\+/g,'a[i]++;')
.replace(/-/g,'a[i]--;')
.replace(/>/g,'i++;')
.replace(/</g,'i--;')
.replace(/\./g,'o+=String.fromCharCode(a[i]);')
.replace(/,/g,'a[i]=u.charCodeAt(j++);')
.replace(/^/,'var a=new Array(1000).join(\'0\').split(\'\'),i=500,o=\'\',u=prompt(\'Enter input if needed\'),j=0;')
.replace(/$/,'alert(o)')
)

I guess I wrote a brainfuck interpreter in javascript.

The example above simply ouputs Hello World! and ignore the input (no , symbol).
But that works with inputs too ! For example, try ,+>,+>,+>,+<<<.>.>.>. and type golf in the dialog. It will ouputs the next characters in ASCII table : hpmg

share|improve this answer
3  
+1 for the humour in stating that brainfuck is more understandable than JavaScript. –  Nigel Nquande yesterday
    
Are you sure that the Brainfuck characters inside of the replace statements don't affect the program? –  Fraxtil 26 mins ago
add comment

CQL - Caffeinated Query Language

(or "SQL on Caffeine")

This may have been somewhat overly ambitious. Here is an attempt to write SQL(ish) declarative code in CoffeeScript. This requires the ECMAScript 6 Proxy feature. You can test it in node with --harmony-proxies.

Let's set up a template for defining proxies. (Taken from Benvie's comment on this issue)

forward = (->
  _slice  = Array.prototype.slice
  _bind   = Function.prototype.bind
  _apply  = Function.prototype.apply
  _hasOwn = Object.prototype.hasOwnProperty

  Forwarder = (target) ->
    @target = target
    this

  Forwarder.prototype =
    getOwnPropertyNames: -> Object.getOwnPropertyNames(@target)
    keys: -> Object.keys(@target)
    enumerate: ->
      i = 0
      keys = []
      for value of @target
        keys[i++] = value
      keys
    getPropertyDescriptor: (key) ->
      o = @target;
      while o
        desc = Object.getOwnPropertyDescriptor o, key
        if desc
          desc.configurable = true;
          return desc;

        o = Object.getPrototypeOf o
    getOwnPropertyDescriptor: (key) ->
      desc = Object.getOwnPropertyDescriptor @target, key
      if desc
        desc.configurable = true
      desc
    defineProperty: (key, desc) -> Object.defineProperty @target, key, desc
    get: (receiver, key) -> @target[key]
    set: (receiver, key, value) ->
      @target[key] = value;
      true
    has: (key) -> key of @target
    hasOwn: (key) -> _hasOwn.call @target, key
    delete: (key) ->
      delete @target[key]
      true
    apply: (receiver, args) -> _apply.call @target, receiver, args
    construct: (args) -> new (_bind.apply @target, [null].concat args);

  forward = (target, overrides) ->
    handler = new Forwarder target;
    for k of Object overrides
      handler[k] = overrides[k]

    if typeof target is 'function'
      return Proxy.createFunction handler,
                                  -> handler.apply this, _slice.call arguments,
                                  -> handler.construct _slice.call arguments
    else
      return Proxy.create handler, Object.getPrototypeOf Object target

  forward
)();

Now define a proxy object and some suspicious global variables and functions:

sql = forward {
  tables: {}

  finalize: ->
    if typeof @activeRows isnt 'function'
      @result = []
      for row in @activeRows
        @result.push (val for val, i in row when @activeTable.columns[i] in @activeColumns)
    delete @activeRows
    delete @activeColumns
    delete @activeTable

  run: (q) ->
    q.call(this)
    @finalize()
    result = @result
    delete @result
    if typeof result isnt 'function' then console.log result
    return result
}, {
  get: (o,name) ->
    if name of @target
      return @target[name];
    (args...) -> {
      name
      args
    }
}

int = Number
varchar = (l) -> String

TABLE = (x) -> x
INTO = (x) -> x
CREATE = (tableData) ->
  name = tableData.name
  table =
    columns: []
  column = tableData.args[0]
  table[column.name] = []
  table.columns.push(column.name)
  while column = column.args[1]
    table[column.name] = []
    table.columns.push(column.name)

  sql.tables[name] = table

  sql.result = "Created table '#{name}'"

INSERT = (table) -> sql.activeTable = sql.tables[table().name]
VALUES = (rows...) ->
  for row in rows
    for val, i in row
      column = sql.activeTable.columns[i]
      sql.activeTable[column].push val

  sql.result = "Inserted #{rows.length} rows"

FROM = (table) ->
  sql.activeTable = sql.tables[table().name]
SELECT = (columns...) ->
  sql.activeColumns = []
  for col in columns
    if typeof col is 'function'
      col = col()

    sql.activeColumns.push col.name

  sql.activeRows = []
  for val in sql.activeTable[sql.activeTable.columns[0]]
    sql.activeRows.push []

  for col in sql.activeTable.columns
    for val, i in sql.activeTable[col]
      sql.activeRows[i].push val

IN = (list) -> { op: 'in', list }
WHERE = (column) ->
  i = sql.activeTable.columns.indexOf(column.name)
  if column.args[0].op is 'in'
    list = column.args[0].list
    sql.activeRows = (row for row in sql.activeRows when row[i] in list)
  else
    console.log 'Not supported!'

ASC = 'asc'
DESC = 'desc'
BY = (x) -> x
ORDER = (column) ->
  i = sql.activeTable.columns.indexOf(column.name)
  order = if column.args[0] is sql.ASC then 1 else -1
  sql.activeRows.sort (a,b) ->
    if a[i] < b[i]
      return -order
    else if a[i] > b[i]
      return order
    else
      return 0

Well that was quite a lot of setup! But now we can do the following (input/output in a console style):

> sql.run ->
    CREATE TABLE @books(
      @title varchar(255),
      @author varchar(255),
      @year int
    );

Create Table 'books'

> sql.run ->
    INSERT INTO @books
    VALUES ['The C++ Programming Language', 'Bjarne Stroustrup', 1985],
           ['Effective C++', 'Scott Meyers', 1992],
           ['Exceptional C++', 'Herb Sutter', 2000],
           ['Effective STL', 'Scott Meyers', 2001];

Inserted 4 rows

> sql.run ->
    SELECT @title, @year FROM @books
    WHERE @author IN ['Bjarne Stroustrup', 'Scott Meyers']
    ORDER BY @year DESC;

[ [ 'Effective STL', 2001 ],
  [ 'Effective C++', 1992 ],
  [ 'The C++ Programming Language', 1985 ] ]

It's not an actual polyglot, but that's not really the point. I know that @ is used for variables in SQL, but I need all the @s for column and table names because I haven't found a way to proxy the global object (and I wouldn't be surprised if it's really not possible - and for a good reason).

I also changed some parentheses into brackets (in particular after VALUES and IN). Unfortunately, what I couldn't figure out at all is a way to allow normal conditionals like year > 2000, because they would evaluate to a boolean right away.

Still this looks a lot like SQL and is definitely more declarative than imperative/functional/object-oriented so it should qualify nicely for the question. I'm actually thinking if I polished the code a bit and supported a few more features, this could be a useful CoffeeScript module.

Anyway, this was fun! :)

For those not too familiar with CoffeeScript, the SQL queries compile to the following JavaScript:

sql.run(function() {
  return CREATE(
    TABLE(
      this.books(
        this.title(varchar(255), 
        this.author(varchar(255), 
        this.year(int)))
      )
    )
  );
});

sql.run(function() {
  INSERT(INTO(this.books));
  return VALUES([...], ['Effective C++', 'Scott Meyers', 1992], [...], [...]);
});

sql.run(function() {
  SELECT(this.title, this.year(FROM(this.books)));
  WHERE(this.author(IN(['Bjarne Stroustrup', 'Scott Meyers'])));
  return ORDER(BY(this.year(thisESC)));
});
share|improve this answer
    
That is quite a lot of setup, but does look good. I am not a CoffeeScript programmer, but it does look great. The @ in SQL is used for session variables. –  Ismael Miguel yesterday
    
I decided to make the keywords global now. Now there are only @s for column and table names. –  m.buettner yesterday
    
Now it looks a lot like SQL! You did a nice work with this one! –  Ismael Miguel yesterday
add comment

x86 assembly in GNU C

No, I didn't just use the asm keyword, since the question established this is for real programmers... this should run fine on ARM.

(Just to prove the point, I didn't "write" the assembly at all - it's the output produced by GCC Clang (503.0.38) for the commented code at the top, blindly translated into macros.)

This only works in 32-bit mode. That's fine since real programmers code to the word size anyway.

#include <stdio.h>
#include <stdint.h>
/*
int fac(int x) {
    if (x < 1) return 1; else return x * fac(x - 1);
}

int fib(int x) {
    if (x < 2) return x; else return fib(x - 1) + fib(x - 2);
}

int main(void) {
    int a = fib(10), b = fac(10);
    printf("%d %d\n", a, b);
    return 0;
}
*/

typedef union REG {
    intptr_t i; int _i; void * v; union REG * r;
} REG;

#define LPAREN (
#define RPAREN )
#define MACRO(N) ); N##_MACRO LPAREN

#define push MACRO(PUSH)
#define pop  MACRO(POP)
#define mov  MACRO(MOV)
#define sub  MACRO(SUB)
#define add  MACRO(ADD)
#define imul MACRO(IMUL)
#define cmp  MACRO(CMP)
#define jge  MACRO(JGE)
#define jmp  MACRO(JMP)
#define call MACRO(CALL)
#define ret  MACRO(RET) _
#define label MACRO(LABEL)

#define NO_OP(X) 

#define PUSH_MACRO(VAL) *(esp -= 4) = (REG)(VAL)
#define POP_MACRO(DST) (DST) = (typeof(DST))(esp->i); esp += 4
#define MOV_MACRO(VAL, DST) (DST) = (typeof(DST))((REG)VAL).i;
#define SUB_MACRO(VAL, DST) CMP_MACRO(VAL, DST); \
    (DST) = (typeof(DST))(((REG)DST).i - ((REG)VAL).i)
#define ADD_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i + ((REG)VAL).i); \
    ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0
#define IMUL_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i * ((REG)VAL).i); \
    ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0
#define CMP_MACRO(L, R) CMP_MACRO_(((REG)L).i, ((REG)R).i)
#define CMP_MACRO_(L, R) (OF = 0, ZF = L == R, SF = (R - L) < 0)
#define JGE_MACRO(TGT) if (SF == OF) { goto TGT; } else {}
#define JMP_MACRO(TGT) goto TGT;
#define CALL_MACRO(PROC) CALL_MACRO_(PROC, __COUNTER__)
#define CALL_MACRO_(PROC, CTR) PUSH_MACRO(CTR - STARTIP); \
    goto PROC; case CTR - STARTIP:
#define RET_MACRO(_) eip = esp->i; esp += 4; if (eip) { continue; } else { goto *finalreturn; }
#define LABEL_MACRO(NAME) NAME

#define MY_ASM(X) do { const int STARTIP = __COUNTER__; \
    switch(eip) { case 0: MY_ASM_1 X } } while (1);
#define MY_ASM_1(X) MY_ASM_2(NO_OP LPAREN 0 X RPAREN;)
#define MY_ASM_2(X) X

#define CAT(L, R) _CAT(L, R)
#define _CAT(L, R) L##R

#define callASM(F) callASM_(F, CAT(_TMP_, __COUNTER__))
#define callASM_(F, LABEL) (({ PUSH_MACRO(0); stackbase = esp; finalreturn = &&LABEL; \
    goto F; LABEL:; }), (intptr_t)eax)


const int STACKSIZE = 4096;
REG callstack[STACKSIZE], * stackbase;
REG * eax, * ecx, * edx, * ebx, * esi, * edi, * esp, * ebp;
int SF, ZF, OF, eip; void * finalreturn;

int main(void) {
    eax = ecx = edx = ebx = esi = edi = esp = ebp = &callstack[STACKSIZE - 1];
    eip = 0;
    finalreturn = &&TOP; TOP:

    PUSH_MACRO(10);
    int a = callASM(_fac);
    PUSH_MACRO(10);
    int b = callASM(_fib);

    printf("%d %d\n", a, b);
    return 0;


    MY_ASM((
    label _fac:                                   // @fac
        push ebp
        mov esp, ebp
        sub 24, esp
        mov 8[ebp], eax
        mov eax, (-8)[ebp]
        cmp 1, (-8)[ebp]
        jge LBB0_2
        mov 1, (-4)[ebp]
        jmp LBB0_3
    label LBB0_2:
        mov (-8)[ebp], eax
        mov (-8)[ebp], ecx
        sub 1, ecx
        mov ecx, *esp
        mov eax, (-12)[ebp]         // 4-byte Spill
        call _fac
        mov (-12)[ebp], ecx         // 4-byte Reload
        imul eax, ecx
        mov ecx, (-4)[ebp]
    label LBB0_3:
        mov (-4)[ebp], eax
        add 24, esp
        pop ebp
        ret

    label _fib:                                   // @fib
        push ebp
        mov esp, ebp
        sub 24, esp
        mov 8[ebp], eax
        mov eax, (-8)[ebp]
        cmp 2, (-8)[ebp]
        jge LBB1_2
        mov (-8)[ebp], eax
        mov eax, (-4)[ebp]
        jmp LBB1_3
    label LBB1_2:
        mov (-8)[ebp], eax
        sub 1, eax
        mov eax, *esp
        call _fib
        mov (-8)[ebp], ecx
        sub 2, ecx
        mov ecx, *esp
        mov eax, (-12)[ebp]         // 4-byte Spill
        call _fib
        mov (-12)[ebp], ecx         // 4-byte Reload
        add eax, ecx
        mov ecx, (-4)[ebp]
    label LBB1_3:
        mov (-4)[ebp], eax
        add 24, esp
        pop ebp
        ret
    ))
}

Just look at all those casts. Casts mean I'm a realer programmer than the compiler, right?

share|improve this answer
    
+1, that's... twisted. ;) I really like how you handled call, in particular. –  Ilmari Karonen 5 hours ago
add comment

F# in C++

Rather unimaginative and nasty abuse of the preprocessor. I thought it'd be fun to alter C++ to look like a completely dissimilar language instead of using a few aliases to make it look like Java or PHP. I'm not really expecting this to garner a ton of upvotes, it's a just-for-fun entry.

#define let int
#define args ( int __, char* args[] ) { int ___ 
#define println printf(
#define exit "\n" ); return 0; }
#include <stdio.h>

let main args =
    println "F# is better than C++"
    exit

Try it here.

Sadly writing something to STDOUT is about all it can do, although I'm sure if someone threw enough witchcraft at it they could make it do more.

share|improve this answer
add comment

Visual Basic 6 (in JavaScript)

'; Main sub-routine \
'; function Main() { ' \
Sub Main() '
    ' Do not throw any errors... \
    On Error Resume Next '; MsgBox = alert

    ' Show a message box... \
    MsgBox(1 / 0) '

    ' Show errors again... \
    On Error GoTo 0 '

    ' Show another message box... ';
    MsgBox("Hello")
    ' ' } ' \
End Sub '

Main()
share|improve this answer
    
Clever. You don't even need most of the semicolons. –  js1568 yesterday
add comment

Brainfuck in JS

[][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[
!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[
+!+[]]]]][([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(
![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!
![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+
[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]
]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[
]+!+[]+!+[]+!+[]]]]+([][[]]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+[]+!+[]]]]+(!!
[]+[])[+[[+[]]]]+(!![]+[])[+[[+!+[]]]]+([][[]]+[])[+[[+[]]]]+([][(![]+[])[+[[
+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!
![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+
[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[
[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!!
[]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]+!+[]
+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]((![]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+
[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]+(!![]+[])[+[[+[]]]
]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[
+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[
+[[+!+[]]]]]+[])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+[+!+[]]+([][(![]+[]
)[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]
]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+
[])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]])()
share|improve this answer
2  
I don't see any brainfuck here. Not even a single char in ><,.- –  Michael yesterday
4  
@Michael: Who said it isn't a program that makes an infinite loop? –  xfix yesterday
    
is this JSF*ck? –  professorfish 5 hours ago
add comment

This is one of the 2005 IOCCC winners, a C programming that, except by that bunch of defines, looks like a java program:

/*
 * Sun's Java is often touted as being "portable", even though my code won't
 * suddenly become uber-portable if it's in Java. Truth is, Java's one of
 * the most ugly, slow, and straitjacketed languages ever. It's popular
 * mainly because people hear the word "portable" and go "ewww".
 *
 * This program, then, is dedicated to bringing about the death of Java. We
 * good coders have been oppressed for too long by the lame language
 * decisions of pointy-haired bosses and academics who should know better. 
 * It's time we stand up against this junk, and bring back the fun in
 * programming! Viva La Revolution!
 */

#define aSet c
#define BufferedReader(x)1
#define byte Y[I][_^1]?do(:):_&1?do(.):do(`):8;++y;}
#define class int N=0,_,O=328,l=192,y=4,Y[80][64]={0},I;struct
#define do(c)a(#c "\b")
#define err c,c
#define getAllStrings(x));q()
#define if(x)b(#x)
#define IOException
#define line c
#define main(a)b(char*x){write(1,"\033[",2),null}main()
#define new
#define null a(x);}a(char*x){write(1,x,strlen(x));try;try;try;try;
#define out c,c
#define println(x)c
#define private int d(int
#define public short c;}c;typedef int BufferedReader;char*F="JF>:>FB;;BII";
#define return {return
#define static f(x){N=(N+x)%6,y--?f(0),f(1),f(4),f(1):++Y[(I=O+N[F]-66)
#define String
#define System c
#define this if(D):1,O=I,I/=16,l<_/32?if(B):l>_/32?if(A):2,l=_,_/=16,byte
#define throws
#define toArray(x)c
#define try for(;--c.c;)
#define void /16][(_=l+N[6+F]-66)/16]?O/=16,l/=32,O<I/16?if(C):O>I/16?this
#define while(k)if(2J),if(7;21H),f(0),f(4),f(4),if(H),/*

import java.io.*;
import java.util.*;

/**
 * A lame Java program.
 * @author  J. Random Worker
 */
class LameJavaApp
{

    /** The infamous Long-Winded Signature From Hell. */
    public static void main(String[] args)
        throws IOException
    {
        /* Don't get me started on this. */
        BufferedReader reader =
            new BufferedReader(new FileReader(args[0]));

        /* What, this long incantation just to print a string? */
        System.err.println("Hello world!");

        /* At least this is sane. */
        String line;
        while ((line = reader.readLine()) != null)
            System.out.println(line.length());
    }

    /**
     * Method with a needlessly long name.
     * @param   aSet        a set (!)
     */
    private String[] getAllStrings(Set<String> aSet)
    {
        /*
         * This dance is needed even in J2SE 5, which has type
         * templates. It was worse before that.
         */
        return aSet.toArray(new String[0]);
    }

}
share|improve this answer
add comment

C# in Whitespace

Okay, first try at one of these, so let's see how it goes.

using System; //very important  

namespace ConsoleApplication1  //namespace: name whatever you want      
{ 
 //start    
 class  Program  //class name:  also anything    
    {
    //main function 
    static void Main(string[] args) {
        for(int i=0;i<10;i++)   writeOutput(i); 
    } //end main    
    static void writeOutput(int i) { Console.WriteLine(i); }    //display output    


    } //class ends here         

}  //close namespace:   also very important     





//yay!

And in case the formatting went screwy from having to put four spaces at the front of each line, here it is again with . for space and # for tab:

using.System;.//very.important#

namespace.ConsoleApplication1..//namespace:#name.whatever.you.want##
{.
.//start#
.class#Program..//class.name:#also.anything#.
#{
....//main.function#
#static.void.Main(string[].args).{
....#for(int.i=0;i<10;i++)#writeOutput(i);#
#}.//end.main#
#static.void.writeOutput(int#i).{.Console.WriteLine(i);.}#//display.output#

.
.#}.//class.ends.here.##

}..//close.namespace:#also.very.important#.#
.




//yay!
share|improve this answer
add comment

Java in Perl

May count as rule breaking, but I don't care. Obviously, it's intended to look like Java program. It prints 20 Fibonacci numbers, in case it isn't obvious.

Requires Inline::Java module to be installed.

use Inline Java => <<'JAVA';
/**
 * @author  Konrad Borowski <[email protected]>
 * @version 0.1.0
 */
class Fibonacci
{
    /**
     * Responsible for storing the number before last generated number.
     */
    private long beforeLastNumber = 0;

    /**
     * Responsible for storing the last generated number.
     */
    private long lastNumber = 1;

    /**
     * Receives the next Fibonacci number.
     * 
     * @return long integer that is the next Fibonacci number
      */
    public long next()
    {
        long temponaryLastNumber = lastNumber;
        lastNumber = beforeLastNumber + lastNumber;
        beforeLastNumber = temponaryLastNumber;
        return temponaryLastNumber;
    }

    /**
     * Outputs the Fibonacci number to standard output.
     */
    public void printFibonacci()
    {
        System.out.println(next());
    }

    /**
     * Outputs the Fibonacci number to standard output given number of
     * times.
     * 
     * @param times number of times to print fibonacci number
     */
    public void printFibonacciTimes(int times)
    {
        int i;
        for (i = 0; i < times; i++) {
            printFibonacci();
        }
    }

    /**
     * Constructor for Fibonacci object. Does nothing.
     */
    public Fibonacci()
    {
        // Do nothing.
    }
}
JAVA

###
 # The executable class that shows 20 Fibonacci numbers.
 ##
package outputFibonacci
{
    ###
     # Shows 20 Fibonacci numbers. This method is public,
     # static, and returns void.
     ##
    sub main()
    {
        # In Perl, -> is object method separator, not a dot. This is stupid.
        new Fibonacci()->printFibonacciTimes(20);
    }
}

# Perl doesn't automatically call main method.
outputFibonacci::main();
share|improve this answer
add comment

JavaScript in Ruby

Number.prototype.times = function(f){
  for (var i=this; --i;) f()
}
end = 0
function do(s) {return new Function(s)}

//;# Ruby starts here:
(5).times(do("alert('hi!'); end"))
share|improve this answer
3  
Isn't this ruby in javascript? Not the other way around? –  shelvacu yesterday
add comment

C in Scala

The bridging layer emulates a more romantic era when strings were still null terminated arrays of bytes.

// Scala is a dynamic language
import scala.language.{ dynamics, postfixOps }

val self = this

val argc = args.length
val argv = args.map(_.getBytes)

type char = Array[Byte]
object char extends Dynamic {
  // This program uses expanded memory
  val buffers = new scala.collection.mutable.LinkedHashMap[String, char]

  // Malloc char buffer
  def applyDynamic(name: String)(length: Int) =
    buffers(name) = new Array(length)

  def **(argv: Array[Array[Byte]]) = argv
}

object & extends Dynamic {
  // dereference char pointer
  def selectDynamic(name: String) = char.buffers(name)
}

def printf(format: String, buffers: char*) =
  println(
    (format /: buffers){ case (msg, buffer) =>
      // Read string until \0 terminator
      val value = new String(buffer.takeWhile(0 !=))
      // Replace next %s token
      msg.replaceFirst("%s", value)
    }
  )

def scanf(format: String, buffers: char*) =
  buffers foreach { buffer =>
    val line = Console.readLine()
    // Write string to char* buffer
    line.getBytes(0, line.length, buffer, 0)
    // Remember to always null terminate your strings!
    buffer(line.length) = 0
  }

val PATH_MAX = 4096

implicit class Argumenter(args: Pair[_, _]) {
  def apply[T](f: => T) = f
}

object int {
  // Passthrough
  def main[T](f: => T) = f
  def argc = self.argc
}

// terminates the string after the first character
// investigate switching to "xor eax, eax" instead of having a hardcoded 0
// might save 3 bytes and valuable CPU time with this trick
val initialize = (_: char)(1) = 0

def exit(value: Int) = sys.exit(value)
// ---HOMEWORK-ASSIGNMENT-START---

int main(int argc, char **argv) {
  if (argc != 0) {
    printf("This program does not take parameters!");
    exit(1);
  }

  // I've copy pasted this code from somewhere
  // Code reuse is essential if we want to be DRY
  char first(PATH_MAX + 1);
  char last(PATH_MAX + 1);

  printf("Enter your first and last name:\n");
  scanf("%s%s", &first, &last);

  // Still learning references, do I need these here?
  // I've performed benchmarks on printf and I think it's faster this way
  printf("Your full name is %s %s", &first, &last);

  initialize(&first);
  printf("Your signature is %s. %s", &first, &last);

  exit(0);
}
share|improve this answer
add comment

Python and... nobody will guess (edit: dc)

Here is some valid python code, but actually the program is written in a very different language:

# Initialize systems 1 and 2
# frame 1, divergency speed and divergency latency
f1ds, f1dl, z1 = [2,2,0]
# frame 2, divergency speed and divergency latency
f2ds, f2dl, z2 = [4,4,1]

# Set the most relevant value of ax (detected by low-energy collision)
ax = 42.424242

# Initialize list of successive energy states
s = [17.98167, 21.1621, 34.1217218, 57.917182]

# Most common value for nz parameter
# TODO: check if value from the article of A. Einstein is better
nz = 10

if z2>nz or ax in s:
  ax += 6
  f1ds = 8
  f2ds = 16
  z1 = 4
  z2 = 9

f1dl += z1
f2dl += z2

# main loop, iterate over all energy states
# Warning: hit Ctrl-C if nuclear explosion occurs and adjust either z or nz
for k in s:
  z = nz + k
  f1dl = f1ds + f2dl * z - z1 + 3.14
  f2dl = f2ds + f1dl * z - z2 + 10
  if k > 10 or z-2 in s:
    nz += 0xac  # hexadecimal coefficient found in famous article by E. Fermi

The code runs in both languages with no error.

The combination is very crazy; I would be happy to wait one day or two before telling which is the other language; please leave comments for guessing.

edit: The language was the stack-based language from dc. You may see here well-known keywords like for, if, or, in, but only the letters matter! The , which has no meaning in dc is turned to a register because the first time it appears is after the letter s (the same for :).

share|improve this answer
    
Unless the code does the same thing in both languages, I suppose a language like Befunge could do the trick. –  Thomas Eding 23 hours ago
    
OK, I edit the code in order to put the language I actually chose. –  ברוכאל 19 hours ago
add comment

SML in Java

I still have some ancient code around from when I started learning Java and tried to use it in a functional style. Slightly cleaned up:

/**
 * Genericised ML-style list.
 */
public class FunctionalList<T> 
{
    private final T head;
    private final FunctionalList<T> tail;

    public FunctionalList(T x, FunctionalList<T> xs) {
        this.head = x;
        this.tail = xs;
    }

    public static <T> FunctionalList<T> cons(T x, FunctionalList<T> xs) {
        return new FunctionalList<T>(x, xs);
    }

    public static <T> T hd(FunctionalList<T> l) {
        return l.head;
    }

    public static <T> FunctionalList<T> tl(FunctionalList<T> l) {
        return l.tail;
    }

    public static int length(FunctionalList<?> l) {
        return len(l, 0);
    }

    private static int len(FunctionalList<?> l, int n) {
        return l == null ? n : len(tl(l), n + 1);
    }

    public static <T> FunctionalList<T> rev(FunctionalList<T> l) {
        return rev(l, null);
    }

    private static <T> FunctionalList<T> rev(FunctionalList<T> a, FunctionalList<T> b) {
        return a == null ? b : rev(tl(a), cons(hd(a), b));
    }

    public static <T> FunctionalList<T> append(FunctionalList<T> a, FunctionalList<T> b) {
        return a == null ? b : cons(hd(a), append(tl(a), b));
    }
}
share|improve this answer
add comment

J and... nobody will guess (edit: dc)

This is my second entry; here is a piece of valid J code, which returns 1:

10 o. 1 r. 2 i. 4 [ ( 0:`1: @. (2&|)) ] 8 #: *:@+: 42

I am waiting one or two day before telling which is the other language running the very same piece of code with no error. Just leave comments for trying to guess.

edit: The other language is the stack-based language from the very ancient Unix calculator dc.

share|improve this answer
1  
It runs without errors in GolfScript, BF, HQ9+, ... –  Peter Taylor yesterday
    
OK, I wasn't aware that such many languages could do it. I edit the code in order to put the language I actually chose. –  ברוכאל 19 hours ago
add comment

Asp in PHP

fskdfkz

Well I know, not very useful.

share|improve this answer
add comment

C++ in C

OK, so you are a C++ programmer, but are forced to use C? No problem, you just have to write some supplementary headers missing in C. For example, here's a valid Hello World program in C:

In the supplementary header file iostream, write:

#include <stdio.h>

#define using volatile int
#define namespace message
#define std = 0
#define message(x) printf("%s\n",x)
#define cout 0
#define endl 0

In file string, write

#define string

In file helloworld.c (your actual C code), write

#include <iostream>
#include <string>

using namespace std;

int main()
{
  string message("Hello world");
  cout << message << endl;
  return 0;
}

And when compiling helloworld.c with a C compiler, instruct the compiler to also look for <...> header files wherever you stored the files iostream and string, for example, if you are compiling with gcc and put the files iostream and string in the current directory, compile with

gcc helloworld.c -o helloworld -I.

Note: The volatile in header iostream is there to enable a warning-free compile even at maximum warning level (a read from a volatile variable is considered to have an effect).

share|improve this answer
add comment

Commodore 64 Basic, BBC Basic etc.

Cheeky entry:

10 PRINT "HELLO WORLD"
20 GOTO 10
RUN

I did think about including Spectrum since you can type GOTO, but it renders GO TO, so technically not the same.

share|improve this answer
add comment

sed and APL

My boss wants me to write sed scripts, but I like rather writing APL all the day. Nevertheless, he is very happy with my job because such scripts run perfectly with his version of sed:

i ← g ← 42
a ← d ← 10
s/s←2⊤42/s←2⊤43/g
s/s[01]*1/s⊣1/g
g

You can try it on my new website with this permalink. It is a compiled to javascript version of GNU APL. Final release will be later with official release of GNU APL, v. 1.3 but you can perfectly use it for your permalinks if you enjoy GNU APL.

share|improve this answer
add comment

dc running a PostScript file

dc can run the following piece of code with no error:

10 10 10 10 10 42 32 10 10
stop % first send a stop
0 0 srand rand
le pop pop 3.14 sin
lt 2 3 lt and pop
le 2 10 le xor
pop pop pop 1 0 0
<< /sox 2 >> [ exch begin sox end ] aload
3.14 floor
share|improve this answer
add comment

LISP in Ada This is not exactly an entry, but a description of what could have been an entry. I came across some code more than ten years ago by a guy who did not understand the US DoD “Ada mandate.” He wanted to use LISP instead of Ada.

Ada has true enumerations (not the disguised integers of C). So in an Ada package, he declared an enumeration type comprising all the primitives of LISP.

Ada allows array literals anywhere an array’s identifier can be. So an array of that enumerated type looks just like a LISP program, but with a comma between the identifiers.

His package body included mutually recursive subprograms to handle all the LISP primitives, and to loop through an array calling the others. I don’t remember how he handled defining and using new functions, as Ada does not allow adding new values to an enumeration at run-time.

So, he could take his LISP program, add an extra paren at each end, insert the commas, put a semicolon after, precede it with “with LISP_faker; Run ” and an Ada compiler would compile it into an executable. I don’t recall every detail—if you know Ada, you’ll realize that nesting is also a problem with what I have described.

The misunderstandings: (1) the so-called mandate allows a waiver if you can persuade the DoD that another language is better for the particular problem; (2) without a waiver, you were required to develop in Ada. Developing in LISP and attaching a clever variation on a LISP interpreter written in Ada was not compliant. But since the people reviewing such things were lawyers and bureaucrats clueless about programming, he probably got away with it. But he could have easily gotten the waiver for the same reason.

share|improve this answer
    
    
That being said, we do look for answers on the site to provide code. If you can include even the most cursory example of your own attempt to implement a bit of Lisp in ADA, this amusing post might avoid its otherwise-likely fate of deletion. Welcome to the site!! –  Jonathan Van Matre 8 hours ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.