neo
neo

Reputation: 69

Using if in scheme to check multiple consequences

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.

Upvotes: 2

Views: 114

Answers (4)

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

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.

Upvotes: 1

ceving
ceving

Reputation: 23794

Use cond:

(define (sign x)
  (cond ((< x 0) -1)
        ((> x 0) 1)
        (else 0)))

Upvotes: 2

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235994

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)))

Upvotes: 2

coredump
coredump

Reputation: 38799

Simple: nest if expressions

(if x a (if y b c))

Upvotes: 1

Related Questions