user=> (def x (lazy-seq (cons (do (println "evaluated") (+ 1 2)) (list 1 2 3)))) #'user/x user=> (def y (cons (do (println "evaluated") (+ 1 2)) (list 1 2 3))) evaluated #'user/y
Archive for February, 2009
Clojure “dumb” simple lazy example
February 22, 2009Clojure immutable collections for Java env
February 22, 2009(Include clojure.jar in your lib path)
List list = new PersistentList("t1");
try {
list.add("t2");
} catch (UnsupportedOperationException e) {
System.out.println("It seems that this operation is not supported.");
}
System.out.println("List size: " + list.size());
Map map = new PersistentArrayMap(new Object[]{"key1", "value1"});
try {
map.put("key2", "value2");
} catch (UnsupportedOperationException e) {
System.out.println("It seems that this operation is not supported.");
}
System.out.println("Map size: " + map.size());
This can be used as an alternative for
java.util.Collections.unmodifiableList(…)
Lazy clojure
February 21, 2009Now, to demonstrate lazy vs. non-lazy behavior in clojure:
(defn create-lazy [i]
(if (zero? i)
()
(lazy-seq (cons nil (create-lazy (dec i))))))
(defn create-non-lazy [i]
(if (zero? i)
()
(cons nil (create-non-lazy (dec i)))))
(create-lazy 1000000)
(try (create-non-lazy 1000000)
(catch java.lang.StackOverflowError e
(println "StackOverflow error")))
Of course, in real life situations, easier methods can be used, like
user=> (replicate 7 nil) (nil nil nil nil nil nil nil) user=>