In Racket, for true you can code "#t" or "true" for true, "#f" or "false" for false
At the beginning, we introduce operator "and" and "or"
;(and expr1 expr2 ... expr-n)
;return true if all the expr's are true
(and (equal? 2 3) (equal? 2 2) true) -> false ;;since (equal? 2 3) is false
;(or expr1 expr2 ... expr-n)
;return true if one of the expr's is true
(or (equal? 2 3) (equal? 2 2) true) -> true ;;since at least one of the expr's is true
1. if syntax
(if A B C)
if A is true, produce B, otherwise produce C
(there is no "else" key work in "if" expression)
(if true 1 2)
-> 1
(if false 1 2)
-> 2
Usually A will be an Boolean test expression
For example, lets say there is an number variable called mark,
and we want to produce "fail" if grade is less than 50.0, else
produce "pass". We can have the code like this:
(define mark 62.0)
(if (< mark 50.0)
"fail"
"pass" )
->"pass"
And for more cases, lets say if we want to break the mark like
if mark is between 50 and 65, output "C";
if mark is between 65 and 80, output "B";
else, output “A”。
We can expand our code expression as,
(define mark 62.0)
(if (< mark 50.0)
"fail"
(if (and (>= mark 50.0) (< mark 65.0))
"C"
(if (and (>= mark 65.0) (< mark 80.0))
"B"
"A")))
->"C"
-
2. cond syntax
(cond (test1 expr1)
(test2 expr2)
....
(else exprn))
cond and if are exchangeable.
For the above if expressions, we can rewrite them using cond
(cond [true 1]
[else 2])
-> 1
(cond [false 1]
[else 2])
-> 2
(define mark 62.0)
(cond [(< mark 50.0) "fail"]
[else
"pass"])
->"pass"
(define mark 62.0)
(cond [(< mark 50.0) "fail"]
[(and (>= mark 50.0) (< mark 65.0)) "C"]
[(and (>= mark 65.0) (< mark 80.0)) "B"]
[else
"A"])
->"C"