Created
September 16, 2010 12:51
-
-
Save zmalltalker/582366 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 true_nor_false;end | |
end | |
class TrueClass | |
def true_nor_false;end | |
end | |
class MaybeClass | |
def if_true;end | |
def if_false;end | |
def true_nor_false | |
yield | |
end | |
end | |
def will_it_rain? | |
maybe | |
end | |
will_it_rain?.if_true { | |
puts "Bring an umbrella" | |
} | |
will_it_rain?.if_false { | |
puts "Wear sunglasses" | |
} | |
will_it_rain?.true_nor_false { | |
puts "Bring an umbrella and wear sunglasses" | |
} |
Why this approach over using a symbol?
def forecast
:maybe
end
bring_umbrella = case forecast
when true
true
when false
false
else
true
end
Haha, didn't think of that, you actually introduced a third alternative to true and false. Clever!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haha!
On a serious note: if we're measuring percentiles, there's probably something more than a simple boolean at play: