0

这是我坚持的过去试卷中的一个问题。请帮忙。

给出了超市账单的类型。账单的每个条目都包含产品的名称、购买了该产品的数量以及单个产品的价格。

type Product = String
type Count = Float -- type chosen for simple arithmetic
type Price = Float
type Bill = [(Count, Product, Price)]

定义一个函数mostExpensive,给定账单将返回账单中最昂贵条目的产品名称和总成本(考虑购买了多少产品)。假设只有一种这样的产品。

4

3 回答 3

6

In Data.List, there's a function called maximumBy that is useful here. It takes a function that does the comparison. To write that function, we'll use a function in Data.Ord called comparing. All we need now is a way to say what we want to compare. So if we define:

calcPrice (k, _, p) = k*p

Then we can get the result using:

maximumBy (comparing calcPrice) items

Armed with that, I think you can solve the problem.

于 2013-04-16T17:18:19.680 回答
0

感谢您的所有帮助,但我将此作为最终答案并与编译器进行了检查,它可以工作:)

mostExpensive :: Bill -> (Price, Product)
mostExpensive [] = (0, "No Products in Bill")
mostExpensive a = head (reverse(sort (map getTotal2 a)))
    where getTotal2 :: (Count, Product, Price) -> (Price, Product)
          getTotal2 (a,b,c) = ((a * c), b)
于 2013-04-16T20:37:15.213 回答
0

这是一种更新手的方法,也可以完成这项工作。可能在优雅等级上得分为负,但非常简单。

如果您正在编写自己的内容,请不要在下面偷看。我敢打赌它比这短:-)

您应该能够调用 ghci 中的每个组件函数来将其拆开。

type Product = String
type Count = Float -- type chosen for simple arithmetic
type Price = Float
type Bill = [(Count, Product, Price)]
type LinePrice = (Product, Price)


myBill :: Bill
myBill = [ (4.0, "Bananas", 0.30), (1.0, "Apple", 0.50), (2.0, "Eggs", 0.25) ]

priceList :: Bill -> [LinePrice]
priceList = map (\(ct,prd,prc) -> (prd, ct*prc))

maxItem :: [LinePrice] -> LinePrice
maxItem lst = maxItem_m ("none",0.0) lst

maxItem_m :: LinePrice -> [LinePrice] -> LinePrice
maxItem_m max [] = max
maxItem_m (prd_m,prc_m) ((prd,prc):rest)
    | prc > prc_m = maxItem_m (prd,prc) rest
    | otherwise   = maxItem_m (prd_m,prc_m) rest

main = do
    let mostExpensive = maxItem $ priceList myBill
    print mostExpensive
于 2013-04-16T18:34:47.533 回答