2011-05-10 57 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)