3値論理 - 論理積 論理和 2008/03/29

3値論理 です。Groovyを使って、論理積 論理和を出力してみました。

論理積
t ^ t = t
t ^ f = f
t ^ u = u
f ^ t = f
f ^ f = f
f ^ u = f
u ^ t = u
u ^ f = f
u ^ u = u
論理和
t ∨ t = t
t ∨ f = t
t ∨ u = t
f ∨ t = t
f ∨ f = f
f ∨ u = u
u ∨ t = t
u ∨ f = u
u ∨ u = u


やはりクロージャーが使えるのはいいですね。
NullPointer例外を発生させるという小手先な方法をとっています。


class PrintThreeValued {
static void main(args) {

def printLogicalProduct = { p, q ->
try {
if(p==null || q==null) throw new NullPointerException()
printf("%s ^ %s = %s%n", p?"t":"f", q?"t":"f", (p && q)?"t":"f");
} catch (e) {
printf("%s ^ %s = %s%n", p == null ? "u" : p?"t":"f",
q == null ? "u" : q?"t":"f", ((p!=null&&!p) || (q!=null&&!q))?"f":"u");
}
}

def printLogicalDisconjunction = { p, q ->
try {
if(p==null || q==null) throw new NullPointerException()
printf("%s ∨ %s = %s%n", p?"t":"f", q?"t":"f", (p || q)?"t":"f");
} catch (e) {
printf("%s ∨ %s = %s%n", p == null ? "u" : p?"t":"f",
q == null ? "u" : q?"t":"f", ((p!=null&&p) || (q!=null&&q))?"t":"u");
}
}

def bs = [true, false, null];

def process = {c ->
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c(bs[i], bs[j]);
}
}

}
println "論理積";
process(printLogicalProduct)
println "論理和";
process(printLogicalDisconjunction)

}
}

: