You Betcha

The hot new game show where

programmers sacrifice their dignity*

in the hopes of winning a T-shirt

*Other risks include loss of confidence, confusion, and hair loss. Losing contestants may be subject to peer pressure and

badgered into making animal noises, participating in ill-conceived medical experiments, or trying new programming techniques.

In a recent study an independent panel concluded that the game was rigged. They were correct. If you have read this far you

have very good eyesight and too much time on your hands.

A group of programmers walk into a bar. The bar tender asks, "What'll it be?" The C programmer says, "You see that bottle?" pointing to a large green bottle marked only with a "*". "Give me whatever's in it." The Lisp programmer says, "Give me (on the bar in front

of me) a glass (a small glass (or plastic cup)) of (imported (German)) beer. (If that's not available, then wine (red (California (Cabernet))).) The assembly language programmer says, "Take a glass from position two in the glass rack and place it on the bar in position

zero ;;in front of you. Take a bottle from position seven in the bottle rack and pour the contents into position zero on the bar. Stop after three seconds. Put the bottle in position seven of the bottle rack. Take the glass from position zero on the bar and place it in position

four on the bar ;;in front of me." The Smalltalk programmer says, "Bartender get vodka bottle. Vodka bottle pour into glass. Hand lift glass. Mouth drink." The Visual Basic programmer says, "You see those two guys sitting over there?" pointing at a big bald guy and a

smaller one wearing glasses. "I'll take whatever they're willing to let me have." The SQL programmer says, "Take all the bottles containing beer, call them 'beers'. Take all the bottles that come from companies with output of less than one million units per year, call them

'micros'. Take the intersection of 'beers' and 'micros', and pour me the first one." The Forth programmer says, "White wine, give me." The Prolog programmer says, "I'll have coke if I want caffeine. I'll have vodka if I want to get drunk. I'll have water if I'm thirsty. I want

caffeine if I need to stay awake. I'm thirsty if it's a hot day. I need to stay awake if I still have work to do today. It's a hot day if it's greater than 80 degrees Fahrenheit. I still have work to do today." The UI designer says, "I'd like a small glass with a thin edge so it's easy

to drink from. It should be large enough to grasp easily, but not so large that it's too heavy. It should have a picture on it of a person drinking (thus showing how to use the glass)." "But what do you want in it?" asks the bar tender. "I don't care," says the UI designer.

...... ... .... .. ... ...... ... ..... ..... ...... ..... .... ...... ..... ...... .. .......... ... .. ..... .... ... ... .... ... ... ... ... ... ... ..... ..... .... .... ....... ... ...

With your hosts Matt Youell

& Markus Roberts

The game is pretty simple:

We show you a code fragment and a question

The first one to buzz in tries to answer the question

If they're wrong the second person gets to try

And if they are wrong the last person gets a shot at it

The first person to answer correctly gets one point

Then we show and briefly discuss the rest of the code

The person with the highest score gets a T-shirt with an incredibly

witty saying on it. The person with the lowest score gets to help

us with the next part of the presentation.

#include <stdio.h>

#include <stdlib.h>

int main(void) {

puts("Hello World!");

int i = 7,n = 999999;

printf("Did you know that %i is %i times %i?\n",n,i,n/i);

return 0;

}

This code is part of a program written in...?

#!/usr/bin/env ruby

def method_missing(msg,*args, &block)

(proc &block).call if block_given?

end

#include <stdio.h>

#include <stdlib.h>

int main(void) {

puts("Hello World!");

int i = 7,n = 999999;

printf("Did you know that %i is %i times %i?\n",n,i,n/i);

return 0;

}

Want to try again?

n = 1;

d = 3;

x = n/d;

This is a little ruby. What is the value of X?

0

#!/usr/bin/env ruby

n = 1;

d = 3;

x = n/d;

print x,”\n”

program Example(Input,Output)

begin

writeln('What''s it Wirth to you?');

end

This code is part of a program written in...?

#include <stdio.h>

#define program int

#define Example(a,b) main()

#define begin {

#define writeln(s) printf(#s); printf("\n")

#define end }

program Example(Input,Output)

begin

writeln('What''s it Wirth to you?');

end

Needs Work

Deal with “'”s

n = 1;

d = 3;

x = n/d;

This still ruby. What is the value of X?

1/3

#!/usr/bin/env ruby

require “mathn”

n = 1;

d = 3;

x = n/d;

print x,”\n”

000010 IDENTIFICATION DIVISION.

000020 PROGRAM-ID. HELLO-WORLD-PROG.

000030 AUTHOR. TIMOTHY R P BROWN.

000040*The standard Hello world program

000050

000060 ENVIRONMENT DIVISION.

000070

000080 DATA DIVISION.

000090 WORKING-STORAGE SECTION.

000100 01 TEXT-OUT PIC X(12) VALUE 'Hello World!'.

000110

000120 PROCEDURE DIVISION.

000130 MAIN-PARAGRAPH.

000140 DISPLAY TEXT-OUT

000150 STOP RUN.

This code is part of a program written in...?

Yeah, it was COBOL.

n = 1;

d = 3;

x = n/d;

Ruby again. What is the value of X?

0.[3]

#!/usr/bin/env ruby

require “mathn”

class Rational

def to_s(*args)

seen = {}

whole_part,n = numerator.divmod denominator

result = whole_part.to_s + "."

while not seen[n]

seen[n] = result.length

digit,n = (n*10).divmod denominator

result += digit.to_s

return result if n == 0

end

result[0...seen[n]]+"["+result[seen[n]..-1]+"]"

end

end

n = 1;

d = 3;

x = n/d;

print x,”\n”

1.767[857142]

Which for 1/3 gives us

Likewise, for 95/96 we'd have

MOV AX, [BP + StartY] ; # of bytes offset

MOV SI, AX ;

AND AX, 0x03 ;

ADD SI, PATTERN_BUFFER ;

This is a fragment of a program written in ...?

#!/usr/bin/env perl

use strict;

use constant StartY => 123;

use constant BP => 0;

use constant PATTERN_BUFFER => 0x7F800;

sub register {

my $reg = shift;

return sub {

return $$reg if( scalar(@_) == 0 ); $$reg = new_value(shift, $$reg);

}

}

sub new_value {

my ($arg, $current_value) = shift;

if( ref($arg) eq 'CODE' ) { return $arg->(); }

elsif( ref($arg) eq 'ARRAY' ) { return @$arg[0]; }

else { return $arg eq "" ? $current_value : $arg; }

}

sub MOV { my $partial = shift; $partial->(shift); }

sub AND { my $register = shift; $register->( $register->() & shift ); }

sub ADD { my $register = shift; $register->( $register->() + shift ); }

my ($AX, $SI) = 0;

sub AX { register(\$AX); }

sub SI { register(\$SI); }

MOV AX, [BP + StartY] ; # of bytes offset

MOV SI, AX ;

AND AX, 0x03 ;

ADD SI, PATTERN_BUFFER ;

print "AX is now: $AX\n";

print "SI is now: $SI\n";

n = 1;

d = 3;

x = n/d;

This time it's C++. What is the value of x?

“One third”

#include <string>

#include <iostream>

#include <sstream>

using namespace std;

class BendyNumber {

int value;

public:

BendyNumber();

void operator=(int val);

string operator/(int val);

};

BendyNumber::BendyNumber() { value = 0; }

void BendyNumber::operator=(int val) { value = val; }

string BendyNumber::operator/(int val) {

string numerator,denominator;

switch (value) {

case 0: return "Nothing";

case 1: numerator = "One "; break;

case 2: numerator = "Two "; break;

case 3: numerator = "Three "; break;

default: numerator = "Many ";

}

switch (val) {

case 0: denominator = "unicorn"; break;

case 1: return numerator; break;

case 2: denominator = "half"; break;

case 3: denominator = "third"; break;

default: denominator = "of many";

}

ostringstream oss;

oss << numerator << denominator;

if (value > 1 and val < 4) { oss << "s"; }

return oss.str();

}

int main() {

BendyNumber n;

int d;

string x;

n = 1;

d = 3;

x = n/d;

cout << x << "\n";

return 0;

}

import π from mathematical constants

function volume(radius,dimensions)

volume(r,0) ≡ 0

volume(r,1) ≡ 2 r

volume(r,2) ≡ π r²

volume(r,3) ≡

4 π r³

--------

3

volume(r,4) ≡

2 4

π r

--------

2

volume(r,5) ≡

2 5

8 π r

----------

15

What widely known and used programming language could this be written in?

#!/usr/env ruby

require "jane_kelly"

________

__ __

__FLEE__

__THIS__

__COOP__

________

_______

__ __

__END__

__THE__

__PEN__

_______

__________

__ __

__ JUMP __

__ THAT __

__SHARK!__

__________

...fly free...

--מנא ,מנא, תקל, ופרסין (Mene, Mene, Tekel u-Pharsin)

import π from mathematical constants

function volume(radius,dimensions)

⋮

It happens to be ruby, but really it

could have been any turing complete

language.

Perfectly valid code in language X, through it may not

have looked like it.

Code that did what it appeared to do, though maybe not in

the way you might have thought.

Something that no one would seriously write.

Some of these examples showed

Perfectly valid code in language X, that also looked

like it was written in language X

...that did something reasonable, though maybe not

what you might have expected

Other examples showed

We're going to explore what it means for code to “look like”

it's written in a language...

...but first we're going to play with electricity.

C

perl

python

ruby

Needs Work

7*i+2

my @x

printf

def f(x)

f(4)

mean,mode = * stats 0..100,&f

prolog

lisp

We tend to program in a compact core of our languages (in some languages

more than others)

C

perl

python

ruby

Needs Work

7*i+2

f(4)

prolog

But that's really a small subset of the realm of all possible languages (not to scale)

What you can

actually do in a

turing-complete

language

C

perl

python

ruby

Needs Work

7*i+2

f(4)

prolog

But the limitation is far more in our use of the languages than in the languages themselves

Proebsting's Law - "Compiler advances double computing power every 18 years."

Greenspun's Tenth Rule of Programming - "Any sufficiently complicated C or Fortran program contains an

ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp."

Gall's Law - "A complex system that works is invariably found to have derived from a simple system that worked."

Clarke's Three Laws

When a distinguished but elderly scientist states that something is possible, he is almost certainly right.

When he states that something is impossible, he is very probably wrong.

The only way of discovering the limits of the possible is to venture a little way past them into the impossible.

Any sufficiently advanced technology is indistinguishable from magic.

Needs Work

Perfectly valid code in language X, through it may not

look like it.

...that does what it appeared to do, though maybe not in

the way you might have thought.

...that people used every day in a production environment,

and no one really objects to.

Now we're going to look at

Perfectly valid code in language X, that also looks

like it was written in language X

...that does something reasonable and expected in the

context though maybe not what is “normal” for the language

We'll also see examples of

getTransport: function() {

return Try.these(

function() { return new XMLHttpRequest() },

function() { return new ActiveXObject('Msxml2.XMLHTTP') },

function() { return new ActiveXObject('Microsoft.XMLHTTP') }

) || false;

}

prototype.js and friends

$('item1', 'item2', 'item3').invoke('hide');

$('link').hasAttribute('href');

class Book < ActiveRecord::Base

has_many :authors, :through => :contributions

def see_also

Book.find_by_title(title) – [self]

end

end

class Author < ActiveRecord::Base

has_many :authorships

has_many :books, :through => :contributions

def coauthors

books.collect_authors - [self]

end

end

class Contribution < ActiveRecord::Base

belongs_to :author

belongs_to :book

end

book = Book.find_or_create_by_ISBN('0201103311')

Rails, ActiveRecord, etc.

module Enumerable

def method_missing(meth,*args)

if meth.to_s =~ /^all_(.*\?)$/

all? { |el| el.send($1,*args) }

elsif meth.to_s =~ /^collect_(.*)\?$/

collect { |el| el.send(meth,*args) }

else

super(meth,*args)

end

end

end

if meth.to_s =~ /^all_(.*\?)$/

instance_eval(%Q{

def #{meth}(*args)

all? { |el| el.send(#{$1.inspect},*args) }

end

})

send(meth,*args)

Or if we think it may get called a lot:

boost, etc.

Needs Work

Why wouldn't you want to do something like this?

Fear of the unknown

Such as job hunting in this economy

Lack of imagination

I can't imagine how this could possibly work

Needs Work

“The Word”

Why you would want to do it

Cleans up your code

To the point it hardly looks like code

Make code easier for domain experts to follow

As long as they aren't programmers

Needs Work

“The Word”

2

-b + Sqrt[ b - 4 a c ]

-----------------------

2 a

2 2 2 x

x Sqrt[r - x ] + r ArcTan[-------------]

2 2

Sqrt[r - x ]

------------------------------------------

2

*http://integrals.wolfram.com/index.jsp?expr=Sqrt[r^2+-+x^2]&random=false

And Wolfram's online integrator* will gladly tell us that the integral of Sqrt[r^2-x^2] is:

Most of us have seen the quadratic formula:

But can we just paste these formulas into our programs?

Heck yeah.

def linearize(s)

lines_above,pivot_line,lines_below = lines_from(s).split_vertically

last_text = nil

pivot_line.split_horizontally.collect { |text,range|

a = linearize lines_above.columns(range)

b = linearize lines_below.columns(range)

'*'.if(adjacent_values(last_text,text)) + case text

when Whitespace: "[#{b}]".unless(b.blank?) +

"**(#{a})".unless(a.blank?)

when A_line_of_dashes: last_text = "((#{a})/(#{b}))"

else last_text = text.strip

end

}.join

end

2

-b + Sqrt[ b - 4 a c ]

-----------------------

2 a

((-b+Sqrt[b**(2)-4*a*c])/(2*a))

def linearize(lines)

lines = lines.split(/\n/) if lines.is_a? String

lines = lines.select { |l| not l =~ /^\s*$/ }

return '' if lines.length == 0

i = (0..lines.length).

sort_by { |i| lines[i] =~ /^( *)(-*)/; [$1.length,-$2.length,i] }.

first { |i| good_divider(lines,i) }

above,below = lines[0...i],lines[(i+1)..-1]

last_text = nil

col = 0

(lines[i]+' '*99).

scan(/(\s+|[-+]?\d+\.?\d*|-+|\w+|.)/).

flatten.

collect { |text|

range = col...(col+=s.length)

implicit_mult =

((last_text=~/[a-z0-9.\)\]]$/i and text=~/^[a-z0-9.\(]/i))? '*' : ''

a = above.collect { |x| x[range] || '' }

b = below.collect { |x| x[range] || '' }

implicit_mult + case text

when /^ *$/: ((b =~ /^\s*$/) ? '' : "[#{ linearize(b)}]") +

((a =~ /^\s*$/) ? '' : "**(#{linearize(a)})")

when /^---+$/: last_text = "((#{linearize(a)})/(#{linearize(b)}))"

else last_text = text.strip

end

}.join

end

The “No Magic Please” version

def lines_from(s)

s = src.split(/\n/).pad_to_match_longest if s.is_a? String

s = s.select { |l| not l.blank? }

def s.split_vertically

i = index_range.

sort_by { |i|

self[i] =~ /^( *)(-*)/

[$1.length,-$2.length,i]

}.

first { |i| good_divider(self,i) } || 0

def (self[i]).split_horizontally

return [] if nil? or blank?

col = 0

scan(/(\s+|[-+]?\d+\.?\d*|-+|\w+|.)/).

flatten.

collect { |x| [x,col...(col+=x.length)] }

end

[rows(0...i),self[i],rows((i+1)..-1)]

end

s

end

module Symbolic_contagen

def method_missing(*args)

A_symbolic_expression.new(self,*args)

end

def coerce(other)

[other.as_symbolic_expression,self]

end

def as_symbolic_expression

self

end

end

class A_symbolic_expression

include Symbolic_contagen

def initialize(*components)

@components = components

end

end

class Symbol

include Symbolic_contagen

end

class Object

def as_symbolic_expression

A_symbolic_expression.new(self)

end

end

class A_symbolic_expression

def param_list

“(#{@components[2..-1]..collect { |a| a.to_s }.join(",")})"

end

def to_s

args = @components

if args[0]

case args.length

when 1: "#{args[0]}"

when 2: "#{args[0]}.#{args[1]}"

else case args[1]

when :+,:-,:*,:/ : "(#{args[0]}#{args[1]}#{args[2]})"

else "#{args[0]}.#{args[1]}#{param_list"

end

end

else "#{args[1]}#{param_list}”

end

end

def inspect

to_s

end

end

def method_missing(meth,*args)

if meth.to_s =~ /^[A-Z]/ and args.length > 0

A_symbolic_expression.new(nil,meth,*args)

else

super

end

end

class Object

def _

A_symbolic_expression.new(self)

end

end

class Object

def apply

self

end

end

class A_symbolic_expression

def substitute(vals)

A_symbolic_expression.new(

*@components.collect { |x|

case

when x == nil : nil

when vals.has_key?(x) : vals[x]

when x.respond_to?(:substitute): x.substitute(vals)

else x

end

}

)

end

def apply

@components[0].apply.send(*@components[1..-1].{|x| x.apply})

end

end

2009-06-12T10:04:44