(def Bonjour-Clojure "Welcome to functional programming")
2011-01-01After the briefest of introductions to functional programming in college(a la Lisp) and dabbling with Scala, I took the functional plunge and started using Clojure recently. At this point, I have only written a couple of small programs and haven’t formed much of an opinion on where it stacks against my current favorite language at the moment(Groovy). This post will follow my usual getting started with a language snippets. I plan to write more entries as I get more familiar with the language. On to the code!
;binding
user=> (def Bonjour-Clojure "Welcome to functional programming")
#’user/Bonjour-Clojure
user=> Bonjour-Clojure
"Welcome to functional programming"
;items in a list can be seperated via a comma or white space..
user=> (= [ 1 2 3] [1,2,3])
true
;count the number of consonants in a string
(defn count-consonants [string] (count ( re-seq #"[^aeiouAEIOU\s]" string )))
user=> (count-consonants "writing code is fun")
10
;count the number of vowels in a string
(defn count-vowels [string] (count ( re-seq #"[aeiouAEIOU\s]" string )))
user=> (count-vowels "lukaskiewicz")
5
;read a file into a list.. any suggestions on other ways are welcome 🙂
;usage (file-lines "string_path_to_file") or to read a webpage ((file-lines "http://javazquez.com")
(defn file-lines [file] (with-open [rdr (clojure.java.io/reader file)] ( set ( line-seq rdr))))
;view objects class
user=>(class "Im a string")
java.lang.String
;length of string
user=>(count "I am 18 chars long")
18
user=>(range 1 9)
(1 2 3 4 5 6 7 8 )
;repeat a digit
user=>(repeat 4 3)
(3 3 3 3)
;list comprehension
user=>(for [fruit ["apple" "orange" "grape"] ] (str fruit))
("apple" "orange" "grape")
;use map to create a new list… #() is a shortcut for an anonymous
user=>(map #(* 2 %1) [1 2 3 4])
(2 4 6 8 )
; also an anonymous function
user=> (map (fn [item](* 2 item)) [1 2 3 4])
(2 4 6 8 )
;simple fiter example on a list using odd?
user=> (filter odd? [1, 2,3,4,5])
(1 3 5)
;factorial using reduce
user=> (reduce * [1 2 3])
6
;if statement
user=> (if true (str "i am true")(str "i am false"))
"i am true"