Ash*_*Ash 3 haskell tuples list wildcard filter
如何通过元组中的第三项过滤此类型的列表:
type Car = (String, [String], Int [String])
Run Code Online (Sandbox Code Playgroud)
我看到了snd
和fst
方法,但在这里我不认为这将工作,我不知道如何不使用'_'
通配符映射.
ham*_*mar 11
没有任何预定义的函数,例如fst
,snd
对于具有两个以上元素的元组.如你所说,你可以使用模式匹配和外卡_
来完成这项工作.
cars = [ ("Foo", ["x", "y"], 2009, ["ab", "cd"]
, ("Bar", ["z"], 1997, [])
]
newCars = filter condition cars
where condition (_, _, n, _) = n > 2005
Run Code Online (Sandbox Code Playgroud)
但是,这通常表明您应该从使用元组更改为记录类型.
data Car = Car { model :: String
, foo :: [String]
, year :: Int
, bar :: [String]
}
cars = [ Car "Foo" ["x", "y"] 2009 ["ab", "cd"]
, Car "Bar" ["z"] 1997 []
]
Run Code Online (Sandbox Code Playgroud)
现在,你可以使用model
,foo
,year
和bar
你一样会使用fst
和snd
对元组.
newCars = filter ((> 2005) . year) cars
Run Code Online (Sandbox Code Playgroud)