Bri
Bri

Reputation: 41

How to replace all occurrences in a nested list in clojure

Given the following sequence:

seq = ( (a b) ( (c d) a ) a )
(replace a z seq) => ( (z b) ( (c d) z ) z )

How can I do that using a lazy sequence and tail recursion?

Upvotes: 4

Views: 247

Answers (1)

A. Webb
A. Webb

Reputation: 26446

Looks like you are wanting to walk through a data structure.

user=> (def s '((:a :b)((:c :d) :a) :a))
#'user/s
user=> (use 'clojure.walk)
nil
user=> (prewalk #(if (= :a %1) :z %1) s)
((:z :b) ((:c :d) :z) :z)

EDIT: Or, if indeed you only need to replace, more simply

user=> (prewalk-replace '{a z} '((a b) ((c d) a)))
((z b) ((c d) z))

Upvotes: 5

Related Questions