Learned some more things today:
1. how to check if an item is in a list
2. for each item in a list / iterate over a list, do something. equivalent java code is mentioned.
; whether an item is in a set. Thanks to Christian Vest Hansen from the clojure google group!
user=> (contains? #{"3e" "2 tired" "1 more"} "3e" )
true
; Thanks to Meikel Brandmeyer of the clojure google group for the use of some, first and filter
; using some: if an item is in a list, return the first match. if not, return nil
user=> (some #{"2 tired"} (list "3e" "2 tired" "1 more"))
"2 tired"
user=> (some #{"clojure is not easy to learn"} (list "3e" "2 tired" "1 more"))
nil
; using first and filter: if an item is in a list, return the first match. if not, return nil
user=> (first (filter #(= % "3e") (list "3r" 25 "3t" "3e")))
"3e"
user=> (first (filter #(= % "34") (list "3r" 25 "3t" "3e")))
nil
; get the first item in a list
user=> (first (list "a" "b" "c"))
"a"
; get items in a list other than the first
user=> (rest (list "a" "b" "c"))
("b" "c")
; for a list with one item, rest returns an empty list
user=> (first (list "a"))
"a"
user=> (rest (list "a"))
()
; do something for each item in a list.
; note that nil is the return value of the doseq function. its not in the list!
user=> (doseq [x '("q" "r" "s")] (println x))
q
r
s
nil
equivalent to the following Java code:
String[] x = {"q", "r", "s"};
for (String s: x) {
System.out.println(s);
}
Of course, due to dynamic typing in clojure, the list could contain practically any data type.
user=> (doseq [x (list "q" "r" "s")] (println x))
q
r
s
nil
; print each item in a sequence
user=> (doseq [x (seq [1 3 4 2 3])] (println x))
1
3
4
2
3
nil
Tuesday, March 9, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment