首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数式编程解

函数式编程解
EN

Stack Overflow用户
提问于 2017-02-02 18:48:58
回答 1查看 83关注 0票数 0

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

代码语言:javascript
复制
data Product = Product String Int
let apple = Product "Apple" 15
let pineapple = Product "Pineapple" 20
let products = [apple, pineapple]

任务:

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

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

EN

回答 1

Stack Overflow用户

发布于 2017-02-02 19:13:45

要执行第二个问题(可以将解决方案修改为解决第三个问题),可以使用递归很容易地解决这个问题。

代码语言:javascript
复制
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

即使你的苹果价格不一样,这也是可行的,尽管那是一家很奇怪的商店。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42010057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档