Lesson 12. Conditional branching with if and cond

 

Whatever your preferred language is, you are probably used to if and switch statements. In Clojure, there is  an if form that is similar to an if statement and a cond form that is similar to a switch statement. In this Lesson, we will explore the similarities and the differences between Clojure if and cond forms and other programming languages if and switch statements.

After completing this lesson, you will be able to:

  • Write simple if expressions
  • Write nested if expressions
  • Write multi-case expressions with cond
  • Draw a flow diagram that describes an if/cond expression
  • Convert a flow diagram into an if/cond expression

In this Lesson, we are going to make usage of some forms that we have explored in Unit 1. Here is a reminder of the forms from Unit 1 that we are going to use in this Lesson:

pos? - returns true when the number is strictly positive

neg? - returns true when the number is strictly negative

zero? - returns true when the number is 0

odd? - returns true when the number is odd

even? - returns true when the number is even

12.1   Simple if expressions

Every programming language provides mechanisms to write code where the flow of the program depends on some condition. The most basic mechanism is what is usually called the if statement. A typical if statement is conceptually made of three parts:

12.2   Nested if expressions

 

12.3   Conditional with cond

 
 
 
 

12.4   Default values with cond

 
 
 

12.5   Summary

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest