2016년 4월 14일 목요일

The first Clojure - 05.Confitionals

IF
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"
"no")
;=> "yes"

IF-NOT
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
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
(cond
(> 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.

WHEN
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")
five
is
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
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")
two
is
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.

댓글 없음:

댓글 쓰기

ETL 솔루션 환경

ETL 솔루션 환경 하둡은 대용량 데이터를 값싸고 빠르게 분석할 수 있는 길을 만들어줬다. 통계분석 엔진인 “R”역시 하둡 못지 않게 관심을 받고 있다. 빅데이터 역시 데이터라는 점을 볼때 분산처리와 분석 그 이전에 데이터 품질 등 데이...