user1910791
user1910791

Reputation: 23

Replace values in a sequence

I'm having problems creating a function that replaces all occurrences of a value in a sequence.

Example: replace 'a' to 'z'; input:

((a b) f ((a b c) (e r) a) a)

expected output:

((z b) f ((z b c) (e r) z) z)

Any ideas?

Upvotes: 2

Views: 252

Answers (2)

Beyamor
Beyamor

Reputation: 3378

prewalk-replace is slightly simpler than @mobyte's answer if you're strictly swapping one value for another:

(def thing '( (a b) f ( (a b c) (e r) a ) a ))

(use '[clojure.walk :only [prewalk-replace]])

(prewalk-replace {'a 'z} thing)
; ((z b) f ((z b c) (e r) z) z

Upvotes: 5

mobyte
mobyte

Reputation: 3752

(use '[clojure.walk :only (postwalk)])

(postwalk #(if (= % 'a) 'z %) '( (a b) f ( (a b c) (e r) a ) a ))
-> ((z b) f ((z b c) (e r) z) z)

Upvotes: 1

Related Questions