简体   繁体   中英

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. 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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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