我是FP和Haskell方面的新手,试图解决一些琐碎的任务。例如,我们有一系列产品:
data Product = Product String Int
let apple = Product "Apple" 15
let pineapple = Product "Pineapple" 20
let products = [apple, pineapple]任务:
在传统的命令式编程中,这非常简单,例如,我可以对此使用不同的计算策略。我怎么才能在Haskell解决这个问题?我应该使用国家单元组还是有其他解决方案?你能提供一些算法步骤或代码吗?
发布于 2017-02-02 19:13:45
要执行第二个问题(可以将解决方案修改为解决第三个问题),可以使用递归很容易地解决这个问题。
totalPriceWithBuy2ApplesGet1HalfOff :: [Product] -> Int
totalPriceWithBuy2ApplesGet1HalfOff = go 0
where
-- It doesn't matter how many apples you've seen, the total
-- price of 0 items is 0
go applesSeen [] = 0
-- If you've seen 2 apples already and the next product is
-- an Apple, give discount
go 2 (Product "Apple" price : products) =
price `div` 2 + go 0 products
-- If applesSeen is some other number and you encounter an apple,
-- add its price and increment applesSeen
go applesSeen (Product "Apple" price : products) =
price + go (applesSeen + 1) products
-- For any other product just add the price to the total and recurse
go applesSeen (Product _ price : products) =
price + go applesSeen products即使你的苹果价格不一样,这也是可行的,尽管那是一家很奇怪的商店。
https://stackoverflow.com/questions/42010057
复制相似问题