【问题标题】:Filter a list of my own type - Tuples?过滤我自己类型的列表 - 元组?
【发布时间】:2011-08-22 07:43:03
【问题描述】:

如何通过元组中的第三项过滤此类型的列表:

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

我看到了sndfst 方法,但在这里我认为这不起作用,我不确定如何在不使用'_' 通配符的情况下进行映射。

【问题讨论】:

  • 我认为您的代码在语法上不正确。 Int 不在这里!
  • Int 后面少了一个逗号。
  • 这听起来像是对 stackoverflow.com/questions/5929377/… 的重新散列,其中已经引入了记录语法和 intercalate

标签: list haskell filter wildcard tuples


【解决方案1】:

对于具有两个以上元素的元组,没有任何预定义函数,例如 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 []
        ]

现在,您可以像在元组上使用 fstsnd 一样使用 modelfooyearbar

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

【讨论】:

  • 这看起来很棒,使用这种方法我如何在这种类型的列表项上使用 init?因此,例如:last foo 这给了我一个类型错误: Car -> [String] 与类型不匹配:[a]??
  • @Ash: last foo 不起作用,因为last 想要一个列表,而foo 是一个函数。如果你想要汽车的最后一个foo,你可以像(last . foo) car一样组合这两个函数。
  • @hammer:但我只从汽车列表中输入了 1 辆汽车 - 所以这不能正常工作:S 你明白我的意思吗?
  • @Ash:如果你能更具体地说明你想要做什么,那就太好了。
  • @Ash:也许你应该创建一个新问题,因为这对 cme​​ts 来说有点大了。包括一个示例,说明您有什么输入以及您希望相应的输出是什么。
【解决方案2】:

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

MissingH 也充满了其他好东西;几乎我所有的项目都在某处或其他地方使用它。

【讨论】:

    【解决方案3】:

    这是我对类似问题的解决方案:

      --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 &lt; getreorder)

    没有用,

    同时

    `过滤器(getstock

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-04
      • 2013-05-03
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多