user3607109
user3607109

Reputation: 1

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

Upvotes: 0

Views: 1259

Answers (1)

Sylwester
Sylwester

Reputation: 48775

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)

Upvotes: 1

Related Questions