Skip to content

Instantly share code, notes, and snippets.

@linneman
Created April 15, 2012 09:49
Show Gist options
  • Save linneman/2391593 to your computer and use it in GitHub Desktop.
Save linneman/2391593 to your computer and use it in GitHub Desktop.
generate test database entries by means of lazy sequences in clojure
(def names
(let [first-names ["Paul" "Lisa" "Andreas" "Paula"
"Gert" "Gerda" "Patrick" "Sabine"
"Gustav" "Monika" "Olaf" "Andrea"
"Ottmar" "Patricia" "Heiner" "Anna"
"Sebastian" "Gudrun" "Christoph" "Silke"
"Max" "Sandy"]
second-names ["Mueller" "Schmidt" "Bauer" "Schuhmacher"
"Stein" "Pfennig" "Baecker" "Schuster"
"Bleichert" "Schulz" "Ludwig" "Mai"
"Roehl" "Richter" "Hofer" "Kling"
"Hauser" "Kaindl" "Kiefer"]
name-vec (vec (for [first-name first-names second-name second-names]
(str first-name " " second-name)))
nn (count name-vec)
name-iter (fn [[n next-name]]
(let [idx (mod n nn)
repeat (quot n nn)
next-name (if (= 0 repeat)
(str (name-vec idx))
(str (name-vec idx) (inc repeat)))]
[(inc n) next-name]
))]
(map #(let [[i n] %] n)
(drop 1 (iterate name-iter [0 nil])))))
(take 5 names)
-> ("Paul Mueller" "Paul Schmidt" "Paul Bauer" "Paul Schuhmacher" "Paul Stein")
(take 5 (drop 100000 names))
-> ("Gerda Schuhmacher240" "Gerda Stein240" "Gerda Pfennig240" "Gerda Baecker240" "Gerda Schuster240")
(take 5 (drop 1000000 names)
-> OUT OF MEMORY ; Why is that since the senqueces are lazy? Have we not lost the head maybe?
@jramb
Copy link

jramb commented Apr 15, 2012

Hehehe, du hast die Antwort doch geschrieben! Loose your head, man! ;-)

"name" steht ja für die gesamte liste, die du im letzten Call auch voll realisierst.
Wie verliert man denn nun "name"? Z.B. indem du "(def names" mit "(defn names[]"
ersetzt.

Dann klappt alles:
(take 5 (names))
oder sogar
(take 5 (drop 10000000 (names)))
;-> ("Monika Kling23924" "Monika Hauser23924" "Monika Kaindl23924" "Monika Kiefer23924" "Olaf Mueller23924")

Gruss, J.

@linneman
Copy link
Author

Tatsächlich, das war's! In der ersten Fassung hatte ich es auch so gemacht, nur fand ich dann den zusätzlichen Funktionsaufruf unschön und plups - Kopf nicht verloren.

Besten Dank für den Tipp,

Gruß,

Otto

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment