Filter out a list of my own type - Tuples?

How can I filter the list of this type with the third element in the tuple:

type Car = (String, [String], Int [String])

I have seen methods sndand fst, but here I do not think this will work, and I am not sure how to match without using a wildcard '_'.

+3
source share
3 answers

There are no predefined functions, such as fstor sndfor tuples with more than two elements. As you said, you can use pattern matching and a wild card _to complete the task.

 cars = [ ("Foo", ["x", "y"], 2009, ["ab", "cd"]
        , ("Bar", ["z"],      1997, [])
        ]

 newCars = filter condition cars
     where condition (_, _, n, _) = n > 2005

However, this usually means that you must switch 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 []
        ]

model, foo, year bar, fst snd .

 newCars = filter ((> 2005) . year) cars
+11
0

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 logical value.

So just saying

filter(getstock < getreorder)

does not work,

and

`filter (getstock <10)

will be

0
source

All Articles