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.

댓글 없음:

댓글 쓰기

블록체인 개요 및 오픈소스 동향

블록체인(block chain) 블록체인은 공공 거래장부이며 가상 화폐로 거래할때 발생할때 발생할 수 있는 해킹을 막는 기술. 분산 데이터베이스의 한 형태로, 지속적으로 성장하는 데이터 기록 리스트로서 분산 노드의 운영자에 의한 임의 조작이 불가...