简体   繁体   English

减去球拍中的数字列表

[英]Subtraction of a list of numbers in racket

I'm trying to subract a list of numbers using recurssion in racket. 我正在尝试使用球拍中的递归计算数字列表。 The function goes like: 功能如下:

(define (sub lst)
 (cond [(empty? lst) 0]
       [ else (- (first lst) (sub (rest lst)))]))

This doesn't seem to be correct as racket performs subtraction from left to right. 这似乎是不正确的,因为球拍从左到右执行减法。 Ie eg: 即例如:

(- 1 2 3 4 6) is suppose to be -14. (- 1 2 3 4 6)假设为-14。 But when i do it in the same way as giving in the list through recurssion, like (list 1 2 3 4 6) it gives the result as 4. How can i solve this? 但是,当我以与通过递归方式给出列表相同的方式进行操作时,例如(list 1 2 3 4 6) ,结果为4。我该如何解决呢?

So your function does this: 因此,您的函数会执行以下操作:

(sub '(1 2 3))      ; ==
(- 1 (- 2 (- 3 0))) ; ==
(- 1 (- 2 3))       ; ==
(- 1 -1)            ; ==
; ==> 2

What you function needs to do is this: 您的职能需要做的是:

(- (- 1 2) 3)  ; ==> -4

There is also special cases for 0 and 1 argument: 还有0和1参数的特殊情况:

(sub '())  ; ==> 0  (identity of - is 0)
(sub '(1)) ; ==> -1 (- identity 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM