Philosophy aside, I amused myself by considering the behaviour of the Smalltalk boolean object a few weeks ago after a brief period of development in Squeak (see also below). You 'talk' to the boolean, and can effectively ask it to do something if it is true or false.
A simple example below, that writes a message to the Transcript window depending on the outcome of the test (which returns a boolean):
a > b
ifTrue:[ Transcript show: 'greater' ]
ifFalse:[ Transcript show: 'less or equal' ]
So, being perverse, what could I do to mimic this behaviour in c#, so I might be able to say:
(a > b)
.IfTrue(() => Console.Write("greater"))
.IfFalse(() => Console.Write("less or equal"));
It's obvious really - use an extension method on the System.Boolean type. This is shown below:
public static class BoolExtension {
public static bool IfTrue(this bool val, Action action) {
if (val) action();
return val;
}
public static bool IfFalse(this bool val, Action action) {
if (!val) action();
return val;
}
}
Please don't misinterpret - I'm not espousing this as a necessarily good idea, more demonstrating that extension methods allow one to 'fake' the presence of interesting constructs present in other languages.
From the squeak website:
Welcome to the World of Squeak!Squeak is a modern, open source, full-featured implementation of the powerful Smalltalk programming language and environment. Squeak is highly-portable - even its virtual machine is written entirely in Smalltalk making it easy to debug, analyze, and change. Squeak is the vehicle for a wide range of projects from multimedia applications, educational platforms to commercial web application development.
No comments:
Post a Comment