Module 1

Introduction to Programming with Clojure

Why Clojure?

Clojure is simple and powerful.

Clojure is all-purpose.

Clojure is fun.

What is Clojure good at?

  • Data processing
  • Concurrent applications
  • Web applications
  • Everything!

Fun things with Clojure

What does Clojure look like?

(+ 3 4)
(max 8 17 2)
(eat "sandwich")

Comments

;; more food code
(eat "cookie") ; nom nom nom
(eat "donut") ; mmm donuts

What is a REPL?

  • Read
  • Eval
  • Print
  • Loop

Simple values

Value types

  • numbers
  • strings
  • booleans
  • keywords

Numbers

;; integers
0
12
-42

;; floats
0.00000072725
10.5
-99.9

;; ratios
1/2
-7/3

Arithmetic

(+ 1 1)  ;=> 1 + 1 = 2
(- 12 4) ;=> 12 - 4 = 8
(* 13 2) ;=> 13 * 2 = 26
(/ 27 9) ;=> 27 / 9 = 3

Infix vs. prefix notation

Languages such as JavaScript use infix notation,
while Clojure only uses prefix notation.

Infix:

1 + 2 * 3 / 4 - 5

Prefix:

(- (+ 1 (/ (* 2 3) 4)) 5)

Infix:

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9

Prefix:

(+ 1 2 3 4 5 6 7 8 9)

Arithmetic with all number types

(+ 4/3 7/8)    ;=> 53/24
(- 9 4.2 1/2)  ;=> 4.3
(* 8 1/4)      ;=> 2
(/ 27/2 1.5)   ;=> 3.0

Sneak Peek at Strings, Booleans, and Keywords

String examples

"Salut tout le monde"
"Prost!"

Keyword examples

:surname
:birth-date
:r2

Boolean examples

true
false

Assigning names to values

def

(def mangoes 3)
(def oranges 5)
(+ mangoes oranges)

Exercise: Basic arithmetic

  • Take your height in centimeters and convert it to inches using arithmetic in Clojure. There are 2.54 centimeters in an inch.
  • Ask two people near you for their height in inches. Find the average of their heights and your height.
  • Bonus: Convert that average to feet and inches. For example: 5 feet and 4 inches. Remember, there are 12 inches in a foot.

  • The feet and the inches will be separate numbers.

    (quot x y) will give you the whole part of the quotient when dividing two numbers.

    (mod x y) will give you the remainder when dividing two numbers.