replace string function

General APL language issues

replace string function

Postby alexeyv on Mon Apr 18, 2016 9:34 pm

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

Postby MBaas on Tue Apr 19, 2016 7:49 am

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:
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.
User avatar
MBaas
 
Posts: 156
Joined: Thu Oct 16, 2008 1:17 am
Location: Gründau / Germany

Re: replace string function

Postby alexeyv on Wed Apr 20, 2016 6:16 pm

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

Postby MBaas on Thu Apr 21, 2016 9:10 am

⎕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...) ;-)
User avatar
MBaas
 
Posts: 156
Joined: Thu Oct 16, 2008 1:17 am
Location: Gründau / Germany


Return to Language

Who is online

Users browsing this forum: No registered users and 1 guest