Replace Surprise

Q&A's, tips, howto's
Locked
Kazimir Majorinc
Posts: 388
Joined: Thu May 08, 2008 1:24 am
Location: Croatia
Contact:

Replace Surprise

Post by Kazimir Majorinc »

I just discovered this unusual behaviour:

Code: Select all

(dolist (i '("first" "second" "third"))
  (println (replace "x" "hej, x" i)))

hej, first
hej, first
hej, first
"hej, first"
Is it bug or feature?

(If "hej, x" is replaced with (copy "hej, x") then everything works as expected. )

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

Probably because replace is destructive and the 2nd and 3rd times through the loop, the argument to replace is "hej, first" instead of "hej, x" so that (replace "x" ...) doesn't find an "x" to replace.

Kazimir Majorinc
Posts: 388
Joined: Thu May 08, 2008 1:24 am
Location: Croatia
Contact:

Post by Kazimir Majorinc »

Yes, it has sense. This example is even simpler.

Code: Select all

(dotimes (i 101)
  (println (inc 0 i))) 
  
(dotimes (i 101)
  (println (inc (copy 0) i))) 

(exit)
I might even like it. But it is surprising.

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

doesn't make sense to me... :) I expect this:

(replace "x" "hej, x" i)

to mean what it says - modification of a string 'constant', not for the string to be silently modified to something else because of a previous operation.

I know I'll never understand newLISP fully... :)

xytroxon
Posts: 296
Joined: Tue Nov 06, 2007 3:59 pm
Contact:

Post by xytroxon »

Well, you can always use the replace function's "second cousin" format ;)

Code: Select all

(dolist (i '("first" "second" "third"))
  (println (format (replace "x" "hej, x" "%s") i)))
Or more clearly and faster...

Code: Select all

(set 'fmtstr (replace "x" "hej, x" "%s"))
(dolist (i '("first" "second" "third"))
  (println (format fmtstr i)))
-- xytroxon
"Many computers can print only capital letters, so we shall not use lowercase letters."
-- Let's Talk Lisp (c) 1976

Locked