我试图用一个值对每个参数求和,我的代码有什么问题?

I am trying to sum each parameter with a value, what is wrong with my code?

我对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 函数,但我不知道如何实现它。

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

如果您想在普通旧方案中使用与 类似方案的标准方案,您需要计划如何识别您的号码使用的货币。也许成对发送它们会更简单实施和使用更简单:

#!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

这是一种计算数字的方法,只需发送 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)