If else clause or cond in Racket
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.
user3400060
Updated on July 18, 2022Comments
-
user3400060 over 1 year
I am trying to write a simple program in Racket that prints 1 if the value of
a
is> 1
, prints0
if the value ofa = 0
and-1
ifa < 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 almost 9 yearsAnd that is why SO should have a "I'm answering this" flag. By the way, you need to fix your last example!
-
Sylwester almost 9 years@Viclib Yes indeed. fixed
-
Greg Hendershott almost 9 yearsOne small note since the question was tagged just
racket
(not alsoscheme
): Although not mandatory it's idiomatic in Racket to use square brackets for certain forms like the clauses incond
. For example(cond [cond expr] [else expr])
.