Total Pageviews

2015/09/03

De Morgan's laws (笛摩根定律) in programming

在命題邏輯和邏輯代數中,De Morgan’s Law [笛摩根定律 (或稱德摩根定理) ] 是關於命題邏輯規律的一對法則。奧古斯塔斯·德摩根首先發現了在命題邏輯中存在著下面這些關係:

  • 非(P 且 Q)=(非 P)或(非 Q)
  • 非(P 或 Q)=(非 P)且(非 Q)

如果忘記什麼是笛摩根定律,可以來複習一下高中數學,高一下數學2-1B觀念08集合的笛摩根定律

在撰寫程式中,一定會在商業邏輯中使用很多if-else的條件式,若善用De Morgan’s Law將其改寫,能將boolean 表示式以更清晰的方式表達

如以下兩個寫法,採用De Morgan’s Law以後,可讀性大幅提昇
1
2
3
4
5
6
7
 // 原本的寫法
 if (!(file_exists && !is_proteced)) {
 }

 // 改採De Morgan’s Law的寫法:把not分配到各項,再反轉and / or
 if (!file_exists || is_proteced) {
 }


Reference
[1] https://www.junyiacademy.org/math-grade-10/root/permutations-and-combinations_a/logic-set-and-arithmetic-theory/v/ymrcargLHN8
[2] https://zh.wikipedia.org/wiki/%E5%BE%B7%E6%91%A9%E6%A0%B9%E5%AE%9A%E5%BE%8B

No comments: