Created
March 3, 2014 06:54
-
-
Save ilovejs/9319716 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(loop [i 0] | |
(if (< i 10) | |
(recur (inc 1)) | |
i)) | |
(str "2 is " (if (even? 2) "even" "odd")) | |
(if (true? false) "impossible!") | |
(defn factorial [x] | |
(with-local-vars [acc 1, cnt x] | |
(while (> @cnt 0) | |
(var-set acc (* @acc @cnt)) | |
(var-set cnt (dec @cnt))) | |
@acc)) | |
;looping is recursive in Clojure, the loop construct is a hack so that something like tail-recursive-optimization works in clojure. | |
(defn my-re-seq [re string] | |
"Something like re-seq" | |
(let [matcher (re-matcher re string)] | |
(loop [match (re-find matcher) ;loop starts with 2 set arguments | |
result []] | |
(if-not match | |
result | |
(recur (re-find matcher) ;loop with 2 new arguments | |
(conj result match)))))) | |
(my-re-seq #"\d" "0123456789") | |
(if (even? 5) | |
(do (println "even") | |
true) | |
(do (println "odd") | |
false)) | |
(if-let [x (even? 3)] | |
(println x) | |
(println "some odd value")) | |
(range 10) | |
(filter even? (range 10)) | |
(str "see: " (seq (filter even? [1 2 3]))) | |
;empty list () will be true, seq will return nil | |
(defn show-evens [coll] | |
(if-let [evens (seq (filter even? coll))] | |
(println (str "the evens are: " evens)) | |
(println "There were no evens."))) | |
(show-evens [2 2]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment