对元组内部的int使用过滤器

时间:2014-07-21 18:00:02

标签: haskell

type MakeUp = (String, String, Int)

stuff :: [MakeUp]
stuff =[("eye liner","MAC",250),("foundation","YSL",800),("toner","GIVENCHY",700),("lip gloss","BENEFIT",900),("bronzer","BENEFIT",500)]

listAllSold :: String -> [MakeUp] -> [MakeUp] 
listAllSold nameOfBrand stuff = [] 

mostSold :: [MakeUp] -> [MakeUp]
mostSold stuff = []

listAllSold "BENEFIT" stuff应该给出:

[("lip gloss","BENEFIT",900),("bronzer","BENEFIT",500)]

mostSold stuff应该给出:

("lip gloss","BENEFIT",900) 

因为销售量最大。

我应该如何编写这些功能?使用过滤器?

2 个答案:

答案 0 :(得分:1)

使用元组

可以使用filter

编写第一个函数
listAllSold :: String -> [MakeUp] -> [MakeUp] 
listAllSold nameOfBrand = filter (\(_, n, _) -> n == nameOfBrand)

第二个使用maximumBy

mostSold :: [MakeUp] -> MakeUp
mostSold = maximumBy (\(_, _, a) (_, _, b) -> compare a b)

Live demo

注意:maximumByData.List 导入。

使用数据类型

您应该考虑使用数据类型而不是元组:

data MakeUp
    = MakeUp
        { a :: String
        , b :: String
        , c :: Int }
    deriving (Eq, Show)

然后您可以将listAllSold定义为:

listAllSold :: String -> [MakeUp] -> [MakeUp] 
listAllSold nameOfBrand = filter ((== nameOfBrand) . b)

mostSold as:

mostSold :: [MakeUp] -> MakeUp
mostSold = maximumBy (compare `on` c)

Live demo

注意:maximumByData.List 导入。{ 注意:onData.Function 导入。

答案 1 :(得分:1)

这里有一个提示,为你的元组类型写入访问器函数:

makeupCategory :: MakeUp -> String
makeupCategory (category, company, sold) = category

makeupCompany :: MakeUp -> String
makeupCompany (category, company, sold) = company

makeupAmountSold :: MakeUp -> Int
makeupAmountSold (category, company, sold) = sold

这些功能非常简单,但现在您可以在其他地方使用它们。现在看一下filter的类型:

filter :: (a -> Bool) -> [a] -> [a]

我们想要传递一个MakeUp的列表,所以我们可以说a ~ MakeUp

filter :: (MakeUp -> Bool) -> [a] -> [a]

现在你可以编写一个函数

isProductOf :: String -> MakeUp -> Bool
isProductOf brand makeup = ???

并将其与filter一起使用。