2011-05-10 104 views
3

我怎样才能通过的第三项中的元组过滤这种类型的列表:过滤我自己的类型列表 - 元组?

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

只见sndfst方法,但在这里,我不认为这会工作和林不知道如何不使用映射通配符为'_'

+0

我觉得你的代码是语法不正确吨。 'Int'不在这里! – phynfo 2011-05-10 09:46:03

+0

“Int”后面缺少逗号。 – hammar 2011-05-10 09:52:04

+0

这听起来像是在那里记录语法和'intercalate'已经推出http://stackoverflow.com/questions/5929377/format-list-output-in-haskell的翻版。 – pat 2011-09-26 15:40:59

回答

11

对于具有两个以上元素的元组,没有任何预定义的函数,如fstsnd。正如你所说,你可以使用模式匹配和通配符_来完成这项工作。

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

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

但是,这通常是一个标志,您应该从使用元组更改为记录类型。现在

data Car = Car { model :: String 
       , foo :: [String] 
       , year :: Int 
       , bar :: [String] 
       } 

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

,您可以使用modelfooyearbar,就像您在使用元组和fstsnd

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

这看起来棒极了,使用这种方法我该如何在这种类型的列表项上使用init? 因此,例如像:去年FOO 这给了我一个错误类型:汽车 - > [字符串]不匹配类型:[A]? – Ash 2011-05-10 10:20:02

+0

@Ash:'最后foo'将无法正常工作,因为'last'想要的清单,而'foo'是一个函数。如果你想要一辆汽车的最后一辆'foo',你可以像'(last.foo)car'一样编写这两个函数。 – hammar 2011-05-10 10:24:35

+0

@hammer,但我是从汽车的列表送入功能只有1车 - 这样,才不会正常工作:■你明白我的意思? – Ash 2011-05-10 10:34:19

0

或者您可以使用Data.Tuple.Utils

充满了其他好东西太多;几乎所有的项目都在其他地方使用它。

0

这里是我的一个类似的问题的解决方案:

--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)] 

的关键是要明白,过滤功能需要一个谓语,而不是一个布尔值。

所以,简单地说

filter(getstock < getreorder)

是行不通的,

'过滤器(getstock < 10)