Page 1 of 1

Replace Surprise

Posted: Sun Sep 13, 2009 8:03 pm
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. )

Posted: Sun Sep 13, 2009 8:56 pm
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.

Posted: Sun Sep 13, 2009 9:36 pm
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.

Posted: Mon Sep 14, 2009 5:24 pm
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... :)

Posted: Tue Sep 15, 2009 8:37 am
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