Reputation: 676
Is there a way to describe arbitrary lazy self-recursive data structures in Clojure? Let's say for example I wanted to do something like this:
(def inf-seq (fn rec [] (lazy-seq (cons 42 (rec)))))
(take 3 (inf-seq))
but with a map:
(def inf-map (fn rec [] (??? {:a (rec) :b 42})))
(get-in (inf-map) [:a :a :a :b])
Upvotes: 2
Views: 335
Reputation: 150
Sequence laziness does not apply to deferred function evaluation in Clojure, which you would obviously need for constructing infinitely nested maps.
Try using Delays:
user=> (def inf-map (fn rec [] {:a (delay (rec)) :b 42}))
#'user/inf-map
user=> (inf-map)
{:a #<Delay@4e9f9a19: :pending>, :b 42}
user=> @(:a (inf-map))
{:a #<Delay@5afd479c: :pending>, :b 42}
Upvotes: 2