Search code examples
schemesubtractionbuilt-in

Scheme - n-ary subtraction function issues


I have the following n-ary function I defined:

(define (- . l)
(cond   ((null? l) 0)
        (else (b- (car l) (apply - (cdr l))))))

It works fine for two arguments, but anymore and it starts to add numbers in a strange way and I don't understand why.

Alternatively, I have a check implemented in a different version of this function in case there is only one argument:

(define (- . l)
(cond   ((null? (cdr l)) (b- (b* l 2) l))
        (else (b- (car l) (apply - (cdr l))))))

This second one does not work at all when I change the first condition. Input should be something like (- 10 6 1)


Solution

  • I assume that b- is a binary subtraction, and that you want to mimic the usual subtraction of Scheme, which is a function such that:

    1. with no arguments, gives an error,
    2. with an argument, changes the sign of the argument,
    3. with more than one argument, substracts from the first one all the others.

    Here is a possibile solution (note that I've called the function n-):

    (define (n- . l)
      (define (aux l dec)
        (if (null? l)
            dec
            (aux (cdr l) (b- dec (car l)))))
      (cond ((null? l) (println "Error"))
            ((null? (cdr l)) (b- 0 (car l)))
            (else (aux (cdr l) (car l)))))
    
    (n-)            ; => Error
    (n- 3)          ; => -3
    (n- 10 6 1)     ; =>  3
    (n- 11 4 8 2)   ; => -3
    

    The auxiliary function subtracts all the numbers from the list first argument to its second argument, and it is defined as a tail recursive function, so that it can be implemented in an iterative way.