Here is the code of ra_copy and a predicate functor? used by it:
[Update: improved version in later post.]
Code: Select all
;; functor? predicate
(define (functor? arg)
(and
(context? arg)
;; (not (nil? (... rets bool instead of functor copy -> faster
(not (nil? (context arg (sym (string arg)))))))
;;
;; 'ref agnostic' copy
(define (ra_copy arg (defaultIfNil nil)) ; defaultIfNil arg may be "" or '()
(if (context? arg)
(if (functor? arg)
(context arg (sym (string arg)))
defaultIfNil)
(if (nil? arg)
defaultIfNil
arg)))
Assumed you want to replace '$' chars in a string in two variants by '#' and by ";;"; leaving the original string intact.
Let code speak for itself: there are three versions of replace-dollar-by-hash-n-semicolons without copy, with copy and with ra_copy in the following example; both results will be returned together in a list.
Just copy/paste all into the interpreter window for getting results:
Code: Select all
;; functor? predicate
(define (functor? arg)
(and
(context? arg)
;; (not (nil? (... rets bool instead of functor copy -> faster
(not (nil? (context arg (sym (string arg)))))))
;;
;; 'ref agnostic' copy
(define (ra_copy arg (defaultIfNil nil)) ; defaultIfNil arg may be "" or '()
(if (context? arg)
(if (functor? arg)
(context arg (sym (string arg)))
defaultIfNil)
(if (nil? arg)
defaultIfNil
arg)))
;;
;;
"----------"
(set 's "$ first\n $ second\n $ third\n")
(set 'S:S s)
"no copy..."
(define (replace-dollar-by-hash-n-semicolons str)
(list
(replace "$" str ";;")
(replace "$" str "#")))
;;
(replace-dollar-by-hash-n-semicolons s) " -> KO"
(replace-dollar-by-hash-n-semicolons S) " -> KO"
"OK s:" s
"KO S:S :" S:S
;;
;;
"----------"
(set 's "$ first\n $ second\n $ third\n")
(set 'S:S s)
"copy..."
(define (replace-dollar-by-hash-n-semicolons str)
(list
(replace "$" (copy str) ";;")
(replace "$" (copy str) "#")))
;;
(replace-dollar-by-hash-n-semicolons s) " -> OK"
(replace-dollar-by-hash-n-semicolons S) " -> KO"
"OK s:" s
"KO S:S :" S:S
;;
;;
"----------"
(set 's "$ first\n $ second\n $ third\n")
(set 'S:S s)
"ra_copy..."
(define (replace-dollar-by-hash-n-semicolons str)
(list
(replace "$" (ra_copy str) ";;")
(replace "$" (ra_copy str) "#")))
;;
(replace-dollar-by-hash-n-semicolons s) " -> OK"
(replace-dollar-by-hash-n-semicolons S) " -> OK"
"OK s:" s
"OK S:S :" S:S
;;
- without copy does not work at all (because of using destructive function replace twice);
- with copy works for vals, but not for refs (both result and original are wrong);
- ra_copy works for both.
- copy-if-functor: for conditionally copying just in case some symbol evaluates to a context with default functor (and avoiding copying in other cases).
In the example above copy-if-functor wouldn't be sufficient, due to having destructive function replace twice (but it may be an optimization for other cases).
Postscript:
Due to being a newbie regarding newLISP, there may be errors in terminology and problems with this approach I don't see so far.