newLISP Fan Club

Forum => newLISP in the real world => Topic started by: Kazimir Majorinc on September 13, 2009, 01:03:48 PM

Title: Replace Surprise
Post by: Kazimir Majorinc on September 13, 2009, 01:03:48 PM
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. )
Title:
Post by: Sammo on September 13, 2009, 01:56:05 PM
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.
Title:
Post by: Kazimir Majorinc on September 13, 2009, 02:36:59 PM
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.
Title:
Post by: cormullion on September 14, 2009, 10:24:29 AM
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... :)
Title:
Post by: xytroxon on September 15, 2009, 01:37:30 AM
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