[英]SICP Exercise 2.19 - how to extend this?
我只是通過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部分,如果以上內容不清楚,則可以鏈接到算法說明。
首先,我想看看實際的硬幣組合構成了進行更改的每種方式,因此我編寫了自己的版本,將每個解決方案打印為列表:
(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 ()))
因此,這就是我遇到的問題:我想修改我的方法,而不是返回整數結果=#種進行更改的方法,並在計算過程中簡單地打印每種方法,而是希望它返回解決方案列表(a列表列表,其長度=進行更改的方式的數量)。 但是,我不知道如何實現這一目標。 使用命令式/ OO語言很容易做到,但是我不知道該怎么做。
有人對如何實現這一目標有任何想法嗎? 對於有經驗的函數式編碼器來說,這似乎應該是一件容易的事。.請幫助滿足我的好奇心,並為您自己一些編碼業力:)
謝謝
(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 '()))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.