Determining if a number is negative in Scheme with one function

2.9k Views Asked by At

I have been going through The Little Schemer and I started getting curious about how to deal with negative numbers. It seemed like a nice challenge to figure out how to build a function to determine if a number is negative or positive.

So far I have this solution:

(define negative?
  (lambda (a)
    (cond
      ((zero? a) #f)
      (else (negativeHelper (sub1 a) (add1 a))))))

(define negativeHelper
  (lambda (a b)
    (cond
      ((zero? a) #f)
      ((zero? b) #t)
      (else (negativeHelper (sub1 a) (add1 b))))))

This looks to be working nicely, but my question is if it is possible to right negative? without the helper function?

1

There are 1 best solutions below

0
On BEST ANSWER

This might not be the answer you're looking for, but there's absolutely nothing wrong with the "helper" function.

You might like nesting inside the negative? function tho

(define (negative? x)
  (define (aux a b)
    (cond ((zero? a) #f)
          ((zero? b) #t)
          (else (aux (sub1 a) (add1 b)))))
  (aux x x))

Verify results

(negative? 4)  ; => #f
(negative? -4) ; => #t
(negative? 0)  ; => #f