Haskell 比较元组列表以查找帐单列表中最昂贵的项目
这是一个过去的试卷上的问题,我一直坚持着。请帮忙 给出了超市账单的类型。账单的每个条目都包含名称 对于一种产品,购买了多少种产品,以及一种产品的价格 单一产品Haskell 比较元组列表以查找帐单列表中最昂贵的项目,haskell,tuples,Haskell,Tuples,这是一个过去的试卷上的问题,我一直坚持着。请帮忙 给出了超市账单的类型。账单的每个条目都包含名称 对于一种产品,购买了多少种产品,以及一种产品的价格 单一产品 type Product = String type Count = Float -- type chosen for simple arithmetic type Price = Float type Bill = [(Count, Product, Price)] 定义一个函数mostExpensive,给定一张账单将返回产品名称
type Product = String
type Count = Float -- type chosen for simple arithmetic
type Price = Float
type Bill = [(Count, Product, Price)]
定义一个函数mostExpensive,给定一张账单将返回产品名称
以及账单中最昂贵条目的总成本(考虑如何
购买了许多产品)。假设只有一个
这样的产品。在
数据.List
中,有一个名为maximumBy
的函数在这里很有用。它使用一个函数进行比较。要编写该函数,我们将使用Data.Ord
中名为comparing
的函数。我们现在所需要的只是一种方式来表达我们想要比较的东西。因此,如果我们定义:
calcPrice (k, _, p) = k*p
然后,我们可以使用以下方法获得结果:
maximumBy (comparing calcPrice) items
有了它,我想你可以解决这个问题。在
Data.List
中,有一个名为maximumBy
的函数在这里很有用。它使用一个函数进行比较。要编写该函数,我们将使用Data.Ord
中名为comparing
的函数。我们现在所需要的只是一种方式来表达我们想要比较的东西。因此,如果我们定义:
calcPrice (k, _, p) = k*p
然后,我们可以使用以下方法获得结果:
maximumBy (comparing calcPrice) items
有了这些,我想你可以解决这个问题。这里有一个更新的方法也可以解决这个问题。可能在优雅等级上得分为负,但很简单 如果你在写自己的东西,不要偷看下面。我打赌它比这个短:-) 您应该能够调用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
这里有一个更为新手的方法也能做到这一点。可能在优雅等级上得分为负,但很简单 如果你在写自己的东西,不要偷看下面。我打赌它比这个短:-) 您应该能够调用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
谢谢你们的帮助,但我用这个作为我的最终答案,并与编译器检查,它的工作:)
谢谢你们的帮助,但我用这个作为我的最终答案,并与编译器检查,它的工作:)