Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else clause or cond in Racket

Tags:

racket

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.

like image 491
user3400060 Avatar asked May 04 '15 23:05

user3400060


1 Answers

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])
like image 191
MaiaVictor Avatar answered Oct 17 '22 04:10

MaiaVictor