Skip to content

Instantly share code, notes, and snippets.

@cjohansen
Forked from zmalltalker/gist:582366
Created September 16, 2010 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjohansen/582385 to your computer and use it in GitHub Desktop.
Save cjohansen/582385 to your computer and use it in GitHub Desktop.
RATIONALE =<<_END
The case for a maybe:
We all know true and false, right? Larry Wall once said that truth should be
considered evident; therefore anything in Perl is either true or false, along with
anything else it may be. Truth is just an aspect.
And we use it easily, with the if/else construct:
if something
do_something
else
do_something_else
end
How about the cases where we don't know? Let's say you're a meteorologist, and somone asks
if it will rain tomorrow. Let's say you don't know, it's a 50/50 chance of each. Would you
accept being forced in to answering yes or no?
if it_will_rain?
bring_an_umbrella
else
wear_sunglasses
else
bring_an_umbrella
wear_sunglasses
end
Makes sense, doesn't it?
Let's give it a try
_END
require 'singleton'
class MaybeClass
include Singleton
def to_s
"maybe"
end
end
class Object
def maybe
MaybeClass.instance
end
end
puts maybe
OMG_AN_OPERATOR=<<_END
But wait, if/else is a language construct, isn't it? What would a Smalltalker do in this situation?
In Smalltalk, there is no if/else statement. Instead you use methods on true and false, like this:
it_will_rain?.if_true {
bring_an_umbrella
}
Let's try
_END
class TrueClass
def if_true
yield
end
def if_false;end
end
class FalseClass
def if_true;end
def if_false
yield
end
end
false.if_true {
puts "No way"
}
true.if_true {
puts "Why, of course"
}
MAKES_SENSE=<<_END
See where I'm going?
_END
class FalseClass
def yes
self
end
def no
yield
self
end
def maybe
self
end
end
class TrueClass
def yes
yield
self
end
def no
self
end
def maybe
self
end
end
class MaybeClass
def yes
self
end
def no
self
end
def maybe
yield
self
end
end
def will_it_rain?
maybe
end
will_it_rain?.yes {
puts "Bring an umbrella"
}.no {
puts "Wear sunglasses"
}.maybe {
puts "Bring an umbrella and wear sunglasses"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment