Any object-oriented language (or any language with polymorphism at runtime) can implement conventions as a library function, since method submission is already a more general conditional form anyway. Smalltalk, for example, has absolutely no conditions other than sending a method.
There is no need for any compiler magic, except perhaps for syntactic convenience.
In Scala, it would look something like this:
trait MyBooleanLike { def iff[T <: AnyRef](thenn: => T): T def iffElse[T](thenn: => T)(els: => T): T def &&(other: => MyBoolean): MyBoolean def ||(other: => MyBoolean): MyBoolean def nott: MyBoolean } trait MyTruthiness extends MyBooleanLike { def iff[T](thenn: => T) = thenn def iffElse[T](thenn: => T)(els: => T) = thenn def &&(other: => MyBoolean) = other def ||(other: => MyBoolean) = MyTrue def nott = MyFalse } trait MyFalsiness extends MyBooleanLike { def iff[T](thenn: => T): T = null.asInstanceOf[T] def iffElse[T](thenn: => T)(els: => T) = els def &&(other: => MyBoolean) = MyFalse def ||(other: => MyBoolean) = other def nott = MyTrue } abstract class MyBoolean extends MyBooleanLike class MyTrueClass extends MyBoolean with MyTruthiness {} class MyFalseClass extends MyBoolean with MyFalsiness {} object MyTrue extends MyTrueClass {} object MyFalse extends MyFalseClass {}
Just add a little implicit conversion:
object MyBoolExtension { implicit def boolean2MyBoolean(b: => Boolean) = if (b) { MyTrue } else { MyFalse } } import MyBoolExtension._
And now we can use it:
object Main extends App { (2 < 3) iff { println("2 is less than 3") } }
[Note: my type-fu is pretty weak. I had to cheat a little to get it compiled in a reasonable amount of time. Someone who better understands a system like Scala might want to fix it. Also, now when I look at it, 8 classes, traits, and objects, two of them abstract, seem a bit overworked ;-)]
Of course, the same is true for pattern matching. Any language with pattern matching does not need other kinds of conditional expressions, since pattern matching is in any case more general.
[BTW: This is basically a port for this Ruby code. I wrote a couple of years ago for fun.]
JΓΆrg W Mittag
source share