Written September 19, 2012. Tagged Logic, General programming, Ruby.
I learned about De Morgan's laws back in logic class.
There's two of them, and they're very straightforward. All they say is that for any A and B, this is true:
!(a && b) == (!a || !b)
!(a || b) == (!a && !b)
Or in logical representation:
¬(A ∧ B) ⇔ (¬A) ∨ (¬B)
¬(A ∨ B) ⇔ (¬A) ∧ (¬B)
I've found them pretty useful in programming.
Granted, they are fairly trivial and no more than you could figure out yourself with some thinking.
But having a name for these transformations means that you're more likely to recognize when they can be applied, and quicker and more confident about applying them. No need to ponder the truth tables – De Morgan already did.
So if you see this:
if !funny? && !cute?
destroy
end
You know straight off that this is equivalent:
unless funny? || cute?
destroy
end
And if you see this:
if !big? || !heavy?
send_as_letter
end
You won't hesitate to change it to:
unless big? && heavy?
send_as_letter
end
I'm very curious to hear about other transformation rules of logic or mathematics or similar that you've found generally useful in programming, and that might not be widely known.