Thursday, September 10, 2020

#100DaysOfClojure (Day [11] flow-control)

 In Clojure everything is an expression because everything returns a value. Even a block of multiple expressions will return the last value. There are 3 basic flow operators: if, when and do, which themselves are also expressions.


If has the following basic form

if boolean 
    then
    optional else

Here is an example of an if expression
(if true
  "It is true"
  "It is false")
=> "It is true"

The do function lets you wrap multiple expressions and forms and looks as follows
(if true
  (do
    (println "First Form")
    "True Expression")
  (do
    (println "Else Form")
    "False Expression"))
First Form
=> "True Expression"

The when operator is a combination of the if and do without the else expression
(when true
  (println "True Form")
  "True Expression")
True Form
=> "True Expression”

;Or when it evaluates to false 

(when false
  (println “False Form")
  “False Expression")
=> nil
 
You can check if a value is nil with the nil? function as follows
(nil? nil)
=> true

But be aware that the nil in an if expression evaluates to false
(if nil
  (do
    (println "First Form")
    "True Expression")
  (do
    (println "Else Form")
    "False Expression"))
Else Form
=> "False Expression"

Clojure also provides equality = and boolean operators or and and
(= 1 1)
=> true

(and 1 1)
=> 1
(and 1 0)
=> 0

(or 1 1)
=> 1
(or 1 0)
=> 1
(or 0 0)
=> 0

That’s it for today, will see you again tomorrow. Not quite sure what I will cover tomorrow, let it be a surprise…

(println “Bye 4 Now!”) 

No comments: