【问题标题】:SICP Exercise 2.19 - how to extend this?SICP 练习 2.19 - 如何扩展这个?
【发布时间】:2013-01-13 20:04:15
【问题描述】:

我只是通过 SICP 探索函数式编程,并且想知道如何扩展练习 2.19 来做一些更有用的事情(而且这似乎需要副作用)。

该练习涉及一个程序,该程序计算在给定硬币面额列表的情况下,一个给定金额(以便士为单位)可以兑换的方式的数量。解决方案非常简单(cc 代表“count-change”):

(define (cc amount coin-values)
  (cond ((= amount 0) 1)
        ((or (< amount 0) (no-more? coin-values)) 0)
        (else
         (+ (cc amount
                (except-first-denomination coin-values))
            (cc (- amount
                   (first-denomination coin-values))
                coin-values)))))

(define (first-denomination coinTypes) (car coinTypes))
(define (except-first-denomination coinTypes) (cdr coinTypes))
(define (no-more? coinTypes) (null? coinTypes))

您可以查看相关的 SICP 部分here,如果上述内容不清楚,请参阅此链接到算法描述。

我首先想看看硬币的实际组合构成了每种更改方式,因此我编写了自己的版本,将每个解决方案打印为列表:

(define (count-change amount coinTypes)
    (define (cc amount coinTypes currChangeList)
        (cond ((= amount 0) 
                    (display (reverse currChangeList)) 
                    (newline) 
                    1)
              ((or (negative? amount) (null? coinTypes)) 
                    0)
              (else (+ (cc amount (cdr coinTypes) currChangeList)
                       (cc (- amount (car coinTypes)) coinTypes (cons (car coinTypes) currChangeList))))))
    (cc amount coinTypes ()))

所以这就是我卡住的地方:我想修改我的方法,而不是返回一个整数结果 = # of ways to make change,并在计算过程中简单地打印每种方式,我希望它返回一个列表解决方案(列表的列表,其中的长度 = 进行更改的方法数)。但是,我不知道如何实现这一点。在命令式/OO 语言中很容易做到,但我不知道如何在功能上做到这一点。

有人知道如何实现这一目标吗?对于经验丰富的函数式编码器来说,这似乎应该是一件很容易的事情。请帮助满足我的好奇心,并为自己赢得一些编码业力:)

谢谢

【问题讨论】:

  • 因为解决问题比阅读解决方案更有趣:如果cc 的结果不是改变方法的数量,而是它们的列表呢?
  • 感谢您的提示!你说得对,解决问题更有趣

标签: functional-programming lisp scheme sicp


【解决方案1】:
(define (count-change amount coinTypes)
    (define (cc amount coinTypes currChangeList)
        (cond ((= amount 0) 
               (list (reverse currChangeList)))
              ((or (negative? amount) (null? coinTypes)) 
               '())
              (else
                (append
                   (cc amount (cdr coinTypes) currChangeList)
                   (cc (- amount (car coinTypes))
                       coinTypes
                       (cons (car coinTypes) currChangeList))))))
    (cc amount coinTypes '()))

【讨论】:

  • 昨晚睡前写了一个问题,早上我睁开眼睛想到了解决方案,希望没有人回答这个问题......不过感谢您抽出宝贵的时间。打字时,你的比我的更干净优雅。有一些业力:)
猜你喜欢
  • 2012-07-05
  • 2011-11-05
  • 2017-02-03
  • 2010-12-26
  • 2012-12-15
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
相关资源
最近更新 更多