[英]Is pattern matching in Set Comprehensions in Haskell possible, or what is an alternative?
I am trying to work out if it is possible to pattern match in Haskell set comprehensions. 我正在尝试确定是否可以在Haskell集合理解中进行模式匹配。 I have a list of lists containing Tuples, or nested lists and tuples;
我有一个包含元组或嵌套列表和元组的列表。
EG 例如
[[(1,("A",1)), (2,("B",1))], [(0,("A",1)), (3,("B",2)), (2,("C",1))]]
I want to discard the tuples containing "A" and preform arbitrary computations on the others. 我想丢弃包含“ A”的元组,并对其他元组执行任意计算。
I was thinking along the lines: 我一直在思考:
pack(xs:xss) = [package x | x <- xs, x /= (1,("A", 1))] : (pack xss)
pack(_) = []
package x = case x of
(i, ("B", j)) -> (i + j, ("B", j * i))
(i, ("C", j)) -> (i * j, ("C", j + i))
(otherwise) -> x
Where the following might permit wildcards: 以下内容可能允许使用通配符:
x /= (1,("A", 1))
Such as: 如:
x /= (_,("A", _))
It is worth noting that the numbers in the nested tuple will always be of type int, not sure if that helps... 值得注意的是,嵌套元组中的数字将始终为int类型,不确定是否有帮助...
I have looked around but can not see if this is possible, it appears that maybe filtering is a better option as noted below; 我环顾四周,但看不到是否可行,如下所示,似乎过滤是一个更好的选择。 however we are filtering on unknowns.
但是我们正在过滤未知数。
Haskell List Comprehension and Pattern Matching Haskell列表理解和模式匹配
My issue is an abstracted example from a larger piece of work/function but hopefully I have captured the essence of the issue here. 我的问题是从较大的工作/功能中提取的一个抽象示例,但希望我已经在这里抓住了问题的实质。 I am open to alternative suggestions.
我愿意接受其他建议。
If you wanted to filter the elements that match a pattern, you could use a pattern on the left hand side of the <-
, eg 如果要过滤与模式匹配的元素,则可以在
<-
的左侧使用模式,例如
... = [package x | x@(_, ("A", _)) <- xs] : ...
This will throw away anything that doesn't match the pattern. 这将丢弃任何与模式不匹配的内容。
Filtering elements that don't match a pattern isn't quite as nice. 过滤与模式不匹配的元素不是很好。 You could do it using a
case
expression as a guard, but it gets kind of ugly. 您可以使用
case
表达式作为防护来做到这一点,但是它有点难看。
... = [package x | x <- xs, case x of (_,("A", _)) -> False; _ -> True] : ...
A prettier alternative is to move the pattern match into a function. 一个更漂亮的选择是将模式匹配移到一个函数中。
... = [package x | x <- xs, want x] : ...
where want (_,("A", _)) = False
want _ = True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.