生成任意数量变量的真值表的方法 [英] Way on generating a truth table for arbitrary number of variables
问题描述
如何为 [a,b,c]
等输入生成所有可能真/假组合的真值表。
例如:
输入:<
我发现真的很难递归地考虑它!
c $ c> [a,b]输出:
[[(a,True),(b,True)],
[(a,True),(b,False)],
[(a ,假),(b,True)],
[(a,False),(b,False)]]
您如何为 a
?
type TruthTable a = [(a,Bool)]
truthTables :: [a] - > ; [TruthTable a]
no 变量的真值表是什么?
truthTables [] = [[]]
如何为变量 v:vs
构造所有可能的真值表,给出 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]
他们< - truthTables vs
return(this:them)
How does one generate a truth table of all possible true/false combinations for an input like ["a", "b", "c"]
.
I find it really hard to think about it recursively!
For example:
Input: ["a", "b"]
Output:
[ [("a",True), ("b",True)],
[("a",True), ("b",False)],
[("a",False), ("b",True)],
[("a",False), ("b",False)] ]
How do you represent truth tables for variables of type a
?
type TruthTable a = [(a, Bool)]
truthTables :: [a] -> [TruthTable a]
What is your truth table for no variables? There is only one: the one that contains no variable assignments.
truthTables [] = [[]]
How do you construct all possible truth tables for variables v:vs
, given the truth tables for vs
? You take every possible truth table for vs
, and every possible assignment for v
, and combine them:
truthTables (v:vs) = [(v, b):others | b <- [True, False], others <- truthTables vs]
We could have also written it using the Monad
instance of []
:
truthTables [] = return []
truthTables (v:vs) = do
this <- [True, False]
them <- truthTables vs
return (this:them)
这篇关于生成任意数量变量的真值表的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!