2

I found a work around:

(define (sign x)
  (if (positive? x)
      1
      (if (negative? x)
          -1
          0)))

Just started a Scheme class at my university. One of the exercises we got was to define a procedure called sign that takes one number as a parameter, and returns 1 if the number is positive, -1 if the number is negative and 0 if the number is 0.

We had to do this in two ways, the first being the use of cond, this was fairly simple and understandable seeing as the book stated that using cond is best suited for checking multiple expressions. The second way was using if, and I got sort of stuck here, I'm not sure how to check this using if. I'm new to this language, so I'm sorry if this is a bad question.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
neo
  • 69
  • 6
  • 2
    That's nice if you found a solution by yourself, but unlike other forums, it is not necessary (and in fact, discouraged) to add "solved". Instead, you are suppose to accept an answer, even if you write it yourself. – coredump Jan 25 '16 at 11:59
  • Noted, thanks for letting me know! – neo Jan 25 '16 at 14:37

4 Answers4

2

If you have multiple conditions, instead of nesting ifs it'll be wiser to use cond. But if you have to use if notice that you can nest it, taking special care to always provide an "else" part to all the conditions and to properly indent them:

(define (sign x)
  (if (< x 0)
      -1
      (if (> x 0)
          1
          0)))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

Use cond:

(define (sign x)
  (cond ((< x 0) -1)
        ((> x 0) 1)
        (else 0)))
ceving
  • 21,900
  • 13
  • 104
  • 178
1

Simple: nest if expressions

(if x a (if y b c))
coredump
  • 37,664
  • 5
  • 43
  • 77
1

For the sake of adding an other answer, If you're dealing with integers... You could do that!

(define (sign x)
  (if (= x 0)
    0
    (/ x (abs x))))

But / and abs might be more expensive than a simple if, so you shouldn't use that solution in anyway. It's just a reminder that some times, you can have an equivelent result by using maths. If you were sure to not have any 0, you could solve this without if.

Loïc Faure-Lacroix
  • 13,220
  • 6
  • 67
  • 99