If else clause or cond in Racket

21,128

Solution 1

The function you are looking for is already defined under the name sgn.

The reason your implementation doesn't work is that it is incomplete. You want:

(if (= a 0)
    0
    (if (< a 0)
        -1
        1))

Or just the better looking:

(cond 
    [(negative? n) -1]
    [(positive? n)  1]
    [else 0])

Solution 2

So how you describe it you have two consequences and one alternative. I would then have used cond:

(cond ((> a 0) 1)
      ((= a 0) 0)
      (else -1))  ; if it's not greater or equal it has to be less than

With cond each term you can expect all previous to be false, thus the last test is not needed since if it's not greater or equal it has to be less than 0. This is exactly the same as writing:

(if (> a 0)
    1
    (if (= a 0) 
        0
        -1))

The main difference is that it looks slightly better with cond. If you have a need for begin (side effects) then using cond would also be beneficial since it has implicit begin:

(define seen
  (let ((hash (make-hash)))
    (lambda (x) 
      (cond ((hash-ref hash x #f) #t)
            (else (hash-set! hash x #t) #f)))))

The same with if:

(define seen
  (let ((hash (make-hash)))
    (lambda (x) 
      (if (hash-ref hash x #f) 
          #t
          (begin
            (hash-set! hash x #t)
            #f)))))

Its the same but I feel cond wins since it's less indentation and more flat.

Share:
21,128
user3400060
Author by

user3400060

Updated on July 18, 2022

Comments

  • user3400060
    user3400060 over 1 year

    I am trying to write a simple program in Racket that prints 1 if the value of a is > 1, prints 0 if the value of a = 0 and -1 if a < 0 . I wrote the following but looks like it is not taking care of the third condition. Actually, I have not included the third condition so I don't know how to check for all three conditions using 'if' clause. A little guidance is appreciated.

    I am new to Racket. My program is:

    #lang racket
    (define a 3);
    
    
    (if (> a 0)
        0 
        1)
    -1
    

    Thanks in advance.

  • MaiaVictor
    MaiaVictor almost 9 years
    And that is why SO should have a "I'm answering this" flag. By the way, you need to fix your last example!
  • Sylwester
    Sylwester almost 9 years
    @Viclib Yes indeed. fixed
  • Greg Hendershott
    Greg Hendershott almost 9 years
    One small note since the question was tagged just racket (not also scheme): Although not mandatory it's idiomatic in Racket to use square brackets for certain forms like the clauses in cond. For example (cond [cond expr] [else expr]).