About This

If all goes well, this will become a little online Clojure tutorial for the Facebook Clojure Community.

If it doesn't go well, blame me - my name is Carl Smotricz and I'm the only (so far) author.

I'm no Clojure guru. I'm an enthusiast looking to share my enthusiasm with others. Comments, suggestions, criticism, contributions are welcome.

5. Decisions, Decisions!

Some kind of sports ad says "power is nothing without control." It's a bit similar in programming - there's only so much functionality we can write without introducing control constructs.

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