How can I filter a list of this type by the third item in the tuple:
type Car = (S开发者_JAVA技巧tring, [String], Int [String])
I saw the snd
and fst
methods but here i dont think this will work and im not sure how to map without using the '_'
wildcard.
There aren't any pre-defined functions like fst
or snd
for tuples with more than two elements. As you said, you can use pattern matching and the wild card _
to do the job.
cars = [ ("Foo", ["x", "y"], 2009, ["ab", "cd"]
, ("Bar", ["z"], 1997, [])
]
newCars = filter condition cars
where condition (_, _, n, _) = n > 2005
However, this is usually a sign that you should change from using tuples to a record type.
data Car = Car { model :: String
, foo :: [String]
, year :: Int
, bar :: [String]
}
cars = [ Car "Foo" ["x", "y"] 2009 ["ab", "cd"]
, Car "Bar" ["z"] 1997 []
]
Now, you can use model
, foo
, year
and bar
like you would use fst
and snd
on tuples.
newCars = filter ((> 2005) . year) cars
Or you could just use Data.Tuple.Utils
?
MissingH
is full of other good stuff too; almost all of my projects use it somewhere or other.
Here is my solution for a similar problem:
--construct a list of stock records with the number in stock less than the reorder level.
getstock (name, stock, reorder) = stock
getreorder (name, stock, reorder) = reorder
check l = filter (\x ->(getstock x < getreorder x)) l
main = print(check [("RAM",9,10),("ROM",12,10),("PROM",20,21)]); --[("RAM",9,10),("PROM",20,21)]
The key was to understand that the filter function takes a predicate, not a boolean value.
So, simply saying
filter(getstock < getreorder)
would not work,
while
`filter (getstock < 10)
would
精彩评论