Search code examples
functional-programmingsmlsmlnj

Easier way to generate a truth table


I want to create a list of lists in SML, which represents a truth table of the following form:

Example:

[
    [("r",true),("p",true),("q",true)],
    [("r",false),("p",false),("q",true)],
    [("r",false),("p",true),("q",true)], 
    ...
]

I think I could achieve this in two ways: (1) with the cartesian product (2) converting truth table index entry to binary, which would represent an encoded line in the list (e.g. 8(decimal) is 1000(binary) => [("r",true),("p",false),("q",false)]), but I think this is to complicated and there is probably an easier way.

What would be the easiest way to go about this?


Solution

  • fun tt []        = [[]]   
      | tt (x :: xs) =    
        let
          val txs = tt xs    
        in
          map (fn l => (x, true) :: l) txs @
          map (fn l => (x, false) :: l) txs    
        end
    
    
    - tt ["a", "b", "c"];
    val it =
      [[("a",true),("b",true),("c",true)],[("a",true),("b",true),("c",false)],
       [("a",true),("b",false),("c",true)],[("a",true),("b",false),("c",false)],
       [("a",false),("b",true),("c",true)],[("a",false),("b",true),("c",false)],
       [("a",false),("b",false),("c",true)],[("a",false),("b",false),("c",false)]]
      : (string * bool) list list