;; This NetLogo module was created by Mark R. Kramer, ;; who hereby offers it to the NetLogo community. ;; The file initially was an include file. It has been converted to a module, now. ;; The primary reason for writing this code was providing a function `repr` ;; for making a difference between `user-message [1 2 3]` and `user-message ["1" "2" "3"]` ;; by using `user-message repr [1 2 3]` and `user-message repr ["1" "2" "3"]` instead. ;; It should work for many similar cases, not limited to `user-message`. ;; Formally: ================================================================================ ;; This program is free software: you can redistribute it and/or modify it under the terms of ;; the GNU General Public License as published by the Free Software Foundation, ;; either version 3 of the License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ;; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;; See the GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License along with this program. ;; If not, see . ;; ========================================================================================== export [repr substitute] ;; Reporter: `repr` ;; Argument: `data` : any NetLogo value ;; Returns: a string representation of `data` including quotes on nested strings ;; makes the distinction between `[1 2 3]` and `["1" "2" "3"]` as in `show` ;; whereas `print` and `word` will remove the quotes ;; example use: `user-message repr ["1" "2" "3"]` shows `["1" "2" "3"]` on screen ;; contrary to `write` does accept any NetLogo types to-report repr [data] if is-list? data [ set data map repr data report (word data) ] if is-string? data [ ;; take care: first substitute existing backslashes set data substitute data "\\" "\\\\" set data substitute data "\t" "\\t" set data substitute data "\n" "\\n" set data substitute data "\"" "\\\"" report (word "\"" data "\"") ] report (word data) end ;; Reporter: `substitute` ;; Argument: `str` : string in which to replace occurrences of a substring ;; Argument: `old` : string to replace ;; Argument: `new` : replacement string ;; Returns: original string `str` with all (non-overlapping) occurrences of `old` replaced by `new` ;; for example `substitute "abbbaababaab" "ab" "ba"` gives "babbababaaba" ;; if `str` is not a string, returns `str` ;; if `old` is an empty string, returns `str` to-report substitute [str old new] if not is-string? str [ report str ] if length old = 0 [ report str ] let len_old length old let prefix "" let suffix str while [member? old suffix] [ let pos position old suffix let front substring suffix 0 pos set suffix substring suffix (pos + len_old) (length suffix) set prefix (word prefix front new) ] report (word prefix suffix) end