replace string function
4 posts
• Page 1 of 1
replace string function
Hi,
I've seen some discussion in GNU APL mailing list on how to write a "replace" function, which takes 3 strings - the source string, replace what and replace with.
For example
What is a idiomatic way to write functions like this? I was not able to find any in Yale APL Idioms list.
I've seen some discussion in GNU APL mailing list on how to write a "replace" function, which takes 3 strings - the source string, replace what and replace with.
For example
replace 'this is a string' 'is' 'AA'
thAA AA a string
What is a idiomatic way to write functions like this? I was not able to find any in Yale APL Idioms list.
- alexeyv
- Posts: 56
- Joined: Tue Nov 17, 2015 4:18 pm
Re: replace string function
I'm not sure there is a single agreed-upon idiomatic string-replace and the solution also depends on the interpreter being used...
The Dyalog-idiomatic way to solve this is:
Or, if you can't use ⎕R:
With ss being defined as:
(from Dyalog's dfns.dws)
And if you can't use dfns, here's the trad-translation: (assuming ⎕ML=1):
The Dyalog-idiomatic way to solve this is:
- Code: Select all
('is' ⎕R'AA')'this is a string'
thAA AA a string
Or, if you can't use ⎕R:
- Code: Select all
ss'this is a string' 'is' 'AA'
thAA AA a string
With ss being defined as:
- Code: Select all
ss←{⎕ML←1 ⍝ Approx alternative to xutils' ss.
srce find repl←,¨⍵ ⍝ source, find and replace vectors.
mask←find⍷srce ⍝ mask of matching strings.
prem←(⍴find)↑1 ⍝ leading pre-mask.
cvex←(prem,mask)⊂find,srce ⍝ partitioned at find points.
(⍴repl)↓∊{repl,(⍴find)↓⍵}¨cvex ⍝ collected with replacements.
}
(from Dyalog's dfns.dws)
And if you can't use dfns, here's the trad-translation: (assuming ⎕ML=1):
- Code: Select all
R←ss arg;srce;find;repl;mask;prem;cvex ⍝ Approx alternative to xutils' ss.
srce find repl←,¨arg ⍝ source, find and replace vectors.
mask←find⍷srce ⍝ mask of matching strings.
prem←(⍴find)↑1 ⍝ leading pre-mask.
cvex←(prem,mask)⊂find,srce ⍝ partitioned at find points.
R←(⍴repl)↓∊{repl,(⍴find)↓⍵}¨cvex ⍝ collected with replacements.
-
MBaas - Posts: 156
- Joined: Thu Oct 16, 2008 1:17 am
- Location: Gründau / Germany
Re: replace string function
Thanks, I didn't know about ⎕R! Have to study dfns implementations though.
- alexeyv
- Posts: 56
- Joined: Tue Nov 17, 2015 4:18 pm
Re: replace string function
⎕S/⎕R were introduced with V14 or 14.1 - they add support for regular expressions in search/replace-operations. Very powerful, but sometimes a bit hard to read. (Hmmm, can't remember where I heard this before...) ;-)
-
MBaas - Posts: 156
- Joined: Thu Oct 16, 2008 1:17 am
- Location: Gründau / Germany
4 posts
• Page 1 of 1
Who is online
Users browsing this forum: No registered users and 1 guest
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group