The first Clojure - 05.Confitionals

The most basic example of this is the if form.
(if test consequent alternative)

If the test is true, the consequent is evaluated. If the test is false, and if an alternative form is provided, then it is evaluated instead (otherwise nil is returned).

(if (> 5 2)
;=> "yes"

The if-not macro does the inverse of what the if special form does. The general structure of this macro is

(if-not test consequent alternative)

Here, if the test is false, the consequent is evaluated; else if it’s true and the alternative is provided, it’s evaluated instead. Here’s a quick example:

(if-not (> 5 2) "yes" "no")
;=> "no"

cond allows you to flatten nested trees of if conditions. The general form looks like the following:

(cond & clauses)

Here’s a simple example of using cond:
(def x 1)
;=> #'user/x
(> x 0) "greater!"
(= x 0) "zero!"
:default "lesser!")
;=> "greater!"

As you can see, the clauses are pairs of expressions, each of the form test consequent.
Each test expression is evaluated in sequence, and when one returns true (actually anything other than false or nil), the associated consequent is evaluated and returned.
If none returns a truthy value, you can pass in something that works as a true value (for example, the keyword :default), and the associated consequent is evaluated and returned instead.

Here’s the general form of the when macro:

(when test & body)

This convenient macro is an if (without the alternative clause), along with an implicit do. This allows multiple s-expressions to be passed in as the body. Here’s how it might be used:

(when (> 5 2)
(println "five")
(println "is")
(println "greater")
;=> "done"

Note that there’s no need to wrap the three functions in the body inside a do, because the when macro takes care of this. You’ll find this a common pattern, and it’s a convenience that most macros provide to their callers.

when-not is the opposite of when, in that it evaluates its body if the test returns false or nil. The general form looks similar to that of when:

(when-not test & body)

Here’s an example:

(when-not (< 5 2)
(println "two")
(println "is")
(println "smaller")
;=> "done"

These are some of the many forms that allow programs to handle different kinds of conditional situations. Except for the if special form, they’re all implemented as macros, which also implies that the programmer is free to implement new ones, suited to the domain of the program. In the next section, you’ll see a little more detail about writing test expressions using logical functions.


이 블로그의 인기 게시물

Android Service에서 AlertDialog 띄우기

MongoDB, 설치와 간단 사용법

Android Thread 내에서 UI 핸들링