我基本上对Scheme很新,这是我第二次尝试解决某个问题。
所以我想要做的基本上是将每个参数传递给函数,并使用适当的值 例如:
(sum 3 1 2 0 2) ;would return 228
这是我的代码:
(define (sum one five ten twenty fifty hundred)
(+ (* 1 one)(* 5 five) (* 10 ten) (* twenty 20) (* 50 fifty) (* 100 hundred))
我认为可能的解决方案是使用lambda函数,但我不知道如何实现它。
答案 0 :(得分:1)
OP希望能够传递的参数少于参数。在这种特定情况下,最好使用关键字(命名)参数。这里有你如何做到这一点(在Racket语法中):
(define (total-bills #:ones (ones 0)
#:fives (fives 0)
#:tens (tens 0)
#:twenties (twenties 0)
#:fifties (fifties 0)
#:hundreds (hundreds 0))
(+ ones (* fives 5) (* tens 10) (* twenties 20) (* fifties 50) (* hundreds 100)))
(每个变量名后面的0
是默认值,也就是说,如果你没有指定它,那么该值是什么。)
使用示例:
> (total-bills #:ones 3 #:fives 1 #:tens 2 #:hundreds 2)
228
答案 1 :(得分:1)
以下是通过仅发送5个参数而不是6个来计算数字的一种方法:
(define sum
(lambda (L skip) ;stores yourList and the number you want to skip
(define loop
(lambda (L L2 total) ;yourList, (1,5,10...) list, running total
(cond
((null? L) (list total)) ;print the total when finish yourList
;if the next number is the skip number, just move on to next value
((= (car L2) skip) (loop L (cdr L2) total))
;otherwise, increase total and send in both lists, minus the head, to the loop
(else (loop (cdr L) (cdr L2) (+ total (* (car L) (car L2)) )))
)
)
)(loop L (list 1 5 10 20 50 100) 0) ;initial values of loop
)
)
;send in your list of numbers, plus the value place you want to skip
(sum (list 3 1 2 0 2) 20) ; ==> 228
但是,我会更容易填写所有你不想要的地方0.一旦你有6个参数,下面的代码就可以了。
(define sum
(lambda (one five ten twenty fifty hundred)
(+ (* 1 one) (* 5 five) (* 10 ten) (* 20 twenty) (* 50 fifty) (* 100 hundred) )
)
)
(sum 3 1 2 0 0 2)
答案 2 :(得分:0)
如果你想在普通旧方案中使用与Chris' answer类似的方案的标准方案,你需要计划如何识别你的号码所在的货币。也许通过成对发送它们将更容易实现并且更易于使用:
#!r6rs
(import (rnrs))
(define (total-bills . args)
(fold-left (lambda (acc x)
(+ acc (apply * x)))
0
args))
(total-bills '(5 1) '(2 10) '(3 100)) ; ==> 325
(apply total-bills '((1 3) (5 1) (10 1) (20 2))) ; ==> 58
您可以根据传递给它的货币制定一个专门程序的程序:
#!r6rs
(import (rnrs))
(define (make-currency-procedure . currencies)
(lambda amounts
(fold-left (lambda (acc currency amount)
(+ acc (* currency amount)))
0
currencies
amounts)))
(define small-bills (make-currency-procedure 1 5 10 20))
(define large-bills (make-currency-procedure 10 100 1000 10000))
(small-bills 3 1 1 2) ; ==> 58
(small-bills 0 1 0 1) ; ==> 25
(large-bills 3 1 1 2) ; ==> 21130
(large-bills 0 1 0 1) ; ==> 10100