De Morgan's laws in programming

Written . Tagged General programming, Logic, 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:

de_morgans_laws.rb
1
2
!(a && b) == (!a || !b)
!(a || b) == (!a && !b)

Or in logical representation:

1
2
¬(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:

1
2
3
if !funny? && !cute?
  destroy
end

You know straight off that this is equivalent:

1
2
3
unless funny? || cute?
  destroy
end

And if you see this:

1
2
3
if !big? || !heavy?
  send_as_letter
end

You won’t hesitate to change it to:

1
2
3
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.