Time to meet our first control function, the if!
Remembering that Clojure is all about expressions, if expressions are expressions - they return one of two possible values, depending on a logical condition.
The general syntax is ( if <condition> <then-value> [ <else-value> ] ) .
The square brackets around "else-value" tell us that we don't need to specify an "else" value. In that case, if the condition is not met, the value returned by the if expression (remember, functions always return values) will be nil (which is equivalent to false).
Here's a function that can tell us whether two numbers are in strictly ascending order or not:
Assignment:
Write a function to tell whether three numbers (a, b, c) are in strictly ascending order!(That is, we want a "yes" only if a < b and b < c)
That test on 3 variables requires (at least) two comparisons. With no other help, that calls for a nesting of two, maybe 3 ifs.
An alternative is to use a logical (boolean) expression. The missing piece is the and function.
The syntax is:
( and <logical-condition> <logical-condition> ... <logical-condition> )
... and of course it returns true if all conditions are true, otherwise false.
The or function is very similar, only it returns true if at least one condition is true.
Rewrite the a, b, c ascending test function using just a single if and the and function!

No comments:
Post a Comment