[英]Gen for a custom data type in Haskell
I was trying to make a truth table for a list of strings.我试图为字符串列表制作真值表。 Say, I have a list ["a","b"]
and as an output, I want [[("a",True),("b",True)], [("a",True),("b",False)], [("a",False),("b",True)], [("a",False),("b",False)]]
说,我有一个列表["a","b"]
作为输出,我想要[[("a",True),("b",True)], [("a",True),("b",False)], [("a",False),("b",True)], [("a",False),("b",False)]]
Each of those instances in the truth table are a custom data type defined as真值表中的每个实例都是自定义数据类型,定义为
data TableRow = [(String,Bool)]
Is there any easier way of doing this?有没有更简单的方法来做到这一点? Until now I have been doing this直到现在我一直在这样做
genRow :: [String] -> [TableRow]
genRow [] = []
genRow (x:xs) = ((makeRow x True) : genRow xs) ++
((makeRow x False) : genRow xs)
Quite obviously, this does not quite give me what I expect.很明显,这并不完全符合我的期望。 Note that makeRow
just takes in a String
and a Bool
and returns a TableRow
.请注意, makeRow
只接受一个String
和一个Bool
并返回一个TableRow
。
Is there any cleaner way of doing this?有没有更干净的方法来做到这一点? Thanks谢谢
The problem with your program is that genRow :: [String] -> [TableRow]
generates a list of TableRow
elements, and you cannot use the cons (:)
constructor on a (String,Bool)
and TableRow
since TableRow
is [[(String,Bool)]]
.您的程序的问题在于genRow :: [String] -> [TableRow]
生成一个TableRow
元素列表,并且您不能在(String,Bool)
和TableRow
上使用 cons (:)
构造函数(String,Bool)
因为TableRow
是[[(String,Bool)]]
。
You can however easily use list comprehension for that:但是,您可以轻松地使用列表理解:
genRow :: [String] -> [[(String,Bool)]]
genRow [] = [[]]
genRow (x:xs) = [(x,b):ti | b <- [True,False], ti <- ts] where ts = genRow xs
The first statement should thus generate a list with one element : the empty list []
(not the empty list as result).因此,第一条语句应该生成一个包含一个元素的列表:空列表[]
(不是作为结果的空列表)。 Furthermore we use list comprehension: we iterate over the two Bool
s True
and False
for b
and for each such value, we iterate over the possible values as tails ts
and prepend the (x,b)
to each of the possible tails.此外,我们使用列表推导式:我们对b
的两个Bool
s True
和False
进行迭代,对于每个这样的值,我们将可能的值迭代为尾ts
并将(x,b)
到每个可能的尾前。
This gives:这给出:
*Main> genRow ["A","B","C"]
[[("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)]]
*Main> genRow ["Foo","Bar"]
[[("Foo",True),("Bar",True)],
[("Foo",True),("Bar",False)],
[("Foo",False),("Bar",True)],
[("Foo",False),("Bar",False)]]
(new lines added for readability) (为了可读性添加了新行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.