First clojure examples


(ns firstClojure)

; numbers and simple expessions - same as in Scheme/Racket
(def a 6)

(println a)

(println (+ 2 3))

(println [(+ 2 3)
          (< 3 5)
          (/ 10 5)
          (/ 5 2)
          (+ 1 2 3 4 5)
          (. Math sqrt 4) ; calling a java method
          (. Math pow 2 200)
          (Math/sqrt 4) ; a shorter way of calling a java method
          (Math/pow 2 200)]) 

; lists may be familiar from Scheme/Racket 
(def fruit '("apple" "banana" "strawberry"))

(println (nth fruit 2))

(println (cons "kiwi" fruit))

(println (first fruit))

(println (rest fruit))

; vectors are more common than lists:
(def colors ["red" "green" "blue"])

(println colors)

; can't do 
;("apple" "banana" "strawberry") 
; without '

; define a function 
; defn is a keyword for defining a function
(defn average [x y] (/ (+ x y) 2))

(println (average 3 5))

(defn square [x] (* x x))

; map maps a fucntion over a sequence, returns the result as
; a sequence (that looks like a list)
(println [(map square [1 2 3 4])
          (map square '(1 2 3 4))
          (map average [1 2 3 ] [-1 -2 -3])
          (map average [1 2 3 ] '(-1 -2 -3))
])

(defn starts-a
  [string] 
  (= (.charAt string 0) \a))

(println [(filter even? '(1 2 3 4 5 6 7 8 9 0))
          (filter starts-a fruit)])

(println [(reduce + [1 2 3 4]) 
          (reduce * [1 2 3 4]) 
          (range 1 20 2)
          (reduce + (range 1 20 2))
          (min 2 3)
          (reduce min [1 2 3 4 5]) ; use "reduce" to find the minimum element in a sequence
])

; anonymous functions
; the two functions are equivalent
(println [(map (fn [x] (* x x)) [1 2 3 4])
          (map #(* %1 %1) [1 2 3 4])
])

(println 
          (if (< 2 3) 5 7))

; recursion (a direct definition, not tail-recursive)
(defn fact [n]
  (if (<= n 0) 1
      (* n (fact (- n 1)))))

(println [ "testing factorial:" (fact 4) (fact 0) (fact 7)] )

; checking multiple conditions:
(println [
          "Checking conditions with cond: \n"

          (cond false 1 true 2)

          (cond (= 1 2) 5 (< 3 2) 6 true 7)

          (cond (= 1 2) 5 (< 3 2) 6 false 7) ; returns nil
])


(defn factorial [num]
(loop [n num accum 1]
  (if (<= n 0)
    accum
    (recur (- n 1) (* accum n)))))

(println ["testing loop/recur factorial:" 
          (factorial 4)  
          (factorial 0)
          (factorial 7)
])



(defn every-other [param_list]
  (loop [the_list param_list keep true result []]
    (cond
     (empty? the_list) result
     keep (recur (rest the_list) false (conj result (first the_list)))
     (not keep) (recur (rest the_list) true result))))

(println ["testing every-other:" 
          (every-other [1 2 3 4 5])
          (every-other [])
          (every-other [1])
])

UMM CSci 4651

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.