2016-02-01 40 views
0

如何生成包含所有可能的真/假組合的真值表,如["a", "b", "c"]生成任意數量變量的真值表的方法

我發現真的很難遞歸思考它!

例如: 輸入:["a", "b"] 輸出:

 [ [("a",True), ("b",True)], 
      [("a",True), ("b",False)], 
      [("a",False), ("b",True)], 
      [("a",False), ("b",False)] ] 

回答

4

你怎麼代表a類型的變量真值表?

type TruthTable a = [(a, Bool)] 

truthTables :: [a] -> [TruthTable a] 

什麼是沒有變量的真值表?只有一個:不包含變量賦值的那個。

truthTables [] = [[]] 

你如何構建給出vs真值表變量v:vs所有可能的真值表?你採取一切可能的真值表vs,和每一個可能的分配爲v,並結合他們:

truthTables (v:vs) = [(v, b):others | b <- [True, False], others <- truthTables vs] 

使用[]Monad情況下我們也可以寫它:

truthTables [] = return [] 
truthTables (v:vs) = do 
    this <- [True, False] 
    them <- truthTables vs 
    return (this:them)