Replace Surprise

Started by Kazimir Majorinc, September 13, 2009, 01:03:48 PM

Previous topic - Next topic

Kazimir Majorinc

I just discovered this unusual behaviour:


(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. )
http://kazimirmajorinc.com/\">WWW site; http://kazimirmajorinc.blogspot.com\">blog.

Sammo

#1
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

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


(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.
http://kazimirmajorinc.com/\">WWW site; http://kazimirmajorinc.blogspot.com\">blog.

cormullion

#3
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

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



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


Or more clearly and faster...



(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