Hi,
I am just looking for better Scala ways of doing things, so asking newbie questions. For example:
I wanted to be able to do things like the following:
Given a,b,c which are "boolean":
if (((a nand b) nand c) != (a nand (b nand c))) printf("NAND is not associative")
Where I would cycle through possible a,b,c boolean values. I did that by:
for (i <- 0 to 7) {
val (a,b,c) = (new MyBoolean((i & 4) >> 2 == 1),
new MyBoolean((i & 2) >> 1 == 1),
new MyBoolean((i & 1) == 1))
printf("%d (%s,%s,%s)\n",i,a,b,c)
if (((a nand b) nand c) != (a nand (b nand c))) printf("NAND\n")
}
I think I could simplify that somewhat to:
val (a,b,c) = (new MyBoolean(i & 4 != 0),
new MyBoolean(i & 2 != 0),
new MyBoolean(i & 1 != 0))
Where my MyBoolean class looks like:
class MyBoolean(val p: Boolean) {
def and(q: MyBoolean): MyBoolean = new MyBoolean(p && q.p)
override def toString: String = p.toString
override def equals (o : Any): Boolean = o match {
case m : MyBoolean => p == m.p
case _ => false
}
def and(q: Boolean): MyBoolean = new MyBoolean(p && q)
def or(q: Boolean): MyBoolean = new MyBoolean(p || q)
def or(q: MyBoolean): MyBoolean = or(q.p)
def negate: MyBoolean = new MyBoolean(!p)
def nand(q : Boolean): MyBoolean = new MyBoolean(!(p && q))
def nand(q : MyBoolean): MyBoolean = nand(q.p)
def nor(q : Boolean): MyBoolean = new MyBoolean(!(p || q))
def nor(q : MyBoolean): MyBoolean = nor(q.p)
def xor(q : Boolean): MyBoolean = new MyBoolean((p || q) && !(p && q))
def xor(q : MyBoolean): MyBoolean = xor(q.p)
def implies(q : Boolean): MyBoolean = new MyBoolean(!(p && !q))
def implies(q : MyBoolean): MyBoolean = implies(q.p)
def equiv(q : Boolean): MyBoolean = new MyBoolean(p == q)
def equiv(q : MyBoolean): MyBoolean = equiv(q.p)
}
Is this reasonable, or is there a much better way to go about this? :)
I didn't have luck trying things like:
def nand(p : Boolean, q : Boolean): Boolean = !(p && q)
I couldn't go from there to:
(a nand (b nand c))
As I had hoped (against hope). :) I would really rather not introduce a new type, it would be nice to just have nand, nor, etc ... work with Boolean.
I think my main also cries out for making things less redundant, I use different functions on several lines ... but the only thing that changes is the function name.
def main(args: Array[String]): Unit = {
for (i <- 0 to 7) {
val (a,b,c) = (new MyBoolean((i & 4) != 0),
new MyBoolean((i & 2) != 0),
new MyBoolean((i & 1) != 0))
printf("%d (%s,%s,%s)\n",i,a,b,c)
if (((a nand b) nand c) != (a nand (b nand c))) printf("NAND\n")
if (((a implies b) implies c) != (a implies (b implies c))) printf("IMPLIES\n")
if (((a nor b) nor c) != (a nor (b nor c))) printf("NOR\n")
if (((a xor b) xor c) != (a xor (b xor c))) printf("XOR\n")
if (((a equiv b) equiv c) != (a equiv (b equiv c))) printf("EQUIV\n")
}
}
-Jay