Skip to content

Instantly share code, notes, and snippets.

@krishnabhargav
Last active August 29, 2015 14:04
Show Gist options
  • Save krishnabhargav/884395aa9216ea6ddea8 to your computer and use it in GitHub Desktop.
Save krishnabhargav/884395aa9216ea6ddea8 to your computer and use it in GitHub Desktop.
Clojure Notest
;; http://grimoire.arrdem.com/
;;shows how to define lambda expressions in clojure
;;one form is a shortcut
(defn empty? [string]
(every? #(Character/isWhitespace %) string))
;; this one is a little more explicit
(defn empty2? [string]
(every? (fn [x] (Character/isWhitespace x)) string))
;; let bindings
(let [bindings*] expr*)
;;bindings are in effect for expr only.
;;example:
(defn sum-of-squares [x y]
(let [xs (* x x)
ys (* y y)]
(+ xs ys)))
;;destructuring
(defn destructure-map [{name :name}]
name)
(destructure-map {:name "Krishna", :age 30})
;; :as form keeps the original argument passed and binds it to person
(defn destructure-map-with-as[{name :name :as person}]
(str name " is " (person :age) " years old"))
;;two examples to understand recur
(defn print-down [x]
(let [y (do (println "Binding x to y") x)]
(when (pos? y)
(println "y is " y)
(recur (dec y)))))
(defn print-down [x]
(do
(println "Print-down started")
(loop [y x]
(when (pos? y)
(println y)
(recur (dec y))))))
;;in the above example "print-down" only gets executed once.
;;note that recur can only be at the tail position .. so the last statement in a flow..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment