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)
因为销售量最大。
我应该如何编写这些功能?使用过滤器?
答案 0 :(得分:1)
可以使用filter
:
listAllSold :: String -> [MakeUp] -> [MakeUp]
listAllSold nameOfBrand = filter (\(_, n, _) -> n == nameOfBrand)
第二个使用maximumBy
:
mostSold :: [MakeUp] -> MakeUp
mostSold = maximumBy (\(_, _, a) (_, _, b) -> compare a b)
注意:maximumBy
由Data.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)
注意:maximumBy
由Data.List
导入。{
注意:on
由Data.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
一起使用。