Haskell过滤数据

时间:2018-07-23 12:54:41

标签: haskell

我希望能够过滤以下数据,以便可以查找特定数据,例如,如果我想查找仅包含苹果的商品,则其外观类似于以下输出:[("apple","crate",6),("apple","box",3)]

fruit :: [(String, String, Int)]
fruit = [("apple", "crate", 6), ("pear", "crate", 5), ("mango", "box", 4),
("apple", "box", 3), ("banana", "box", 5), ("pear", "box", 10), ("apricot",
"box", 4), ("peach", "box", 5), ("walnut", "box", 4), ("blueberry", "tray", 10),
 ("blackberry", "tray", 4), ("watermelon", "piece", 8), ("marrow", "piece", 7), 
 ("hazelnut", "sack", 2), ("walnut", "sack", 4)]

first :: (a, b, c) -> a
first (x, _, _) = x

second :: (a, b, c) -> b
second (_, y, _) = y

third :: (a, b, c) -> c
third (_, _, z) = z

1 个答案:

答案 0 :(得分:2)

几种选择:

filter ((=="apple") . first) fruit
[ f | f@("apple",_,_) <- fruit ]

第一个利用您的first投影,检查其结果是否等于"apple"

第二个漏洞利用列表推导,将无法模式匹配的元素丢弃。

也许更基本的方法是使用lambda抽象和相等性。

filter (\(s,_,_) -> s == "apple") fruit