功能编程解决方案

时间:2017-02-02 18:48:58

标签: haskell functional-programming monads

我是FP和Haskell的新手,并尝试解决一些琐碎的任务。例如,我们有一系列产品:

data Product = Product String Int
let apple = Product "Apple" 15
let pineapple = Product "Pineapple" 20
let products = [apple, pineapple]

任务:

  • 计算产品的总价(这很简单,例如我可以使用foldl)
  • 如果每三个苹果的折扣为0.5
  • ,则计算总价
  • 如果购买每两个苹果菠萝是免费的,则计算总价。

在传统的命令式编程中,这很简单,例如我可以使用不同的计算策略。 我怎样才能在Haskell中解决这个问题?我应该使用State monad还是有其他解决方案?你能提供一些算法步骤或代码吗?

1 个答案:

答案 0 :(得分:0)

要做第二个问题(可以修改解决方案以解决第三个问题),这可以使用递归轻松解决

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

即使你的苹果价格不一样,这也会有用,虽然这是一个非常奇怪的商店。