[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Bug-apl] Substring replacement in APL
From: |
Christian Robert |
Subject: |
Re: [Bug-apl] Substring replacement in APL |
Date: |
Tue, 12 Apr 2016 20:57:09 -0400 |
User-agent: |
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.7.2 |
An other way to do that, written some time ago:
⎕cr 'Replace'
z←Line Replace patterns;f;t;P;pos
⍝
⍝ Check what is effectively `Line`
⍝
→((≡Line)≥2)/Enclosed ⍝ Line is an Enclose of things
→(2=⍴⍴Line)/Matrix ⍝ Line is a Matrix
⍝
⍝ Do the job, single vector source, an even number of changes
⍝
patterns←,¨patterns ⍝ Convert scalar to vector
z←,Line ⍝ I only work on vectors
Main: →(0=⍴patterns)/0 ⍝ No more replace to do, so done.
(f t)←2↑patterns ⍝ Get the 'from' and 'to'
patterns←2↓patterns ⍝ drop 2 from the list
P←⌽(∧/[1](¯1+⍳⍴f)⌽f∘.=z)/⍳⍴z ⍝ get the pos where string is found, reverse
order
Loop: →(0=⍴P)/Main ⍝ Until there is none
pos←1↑P ⍝ get the pos
P←1↓P ⍝ drop from future
z←((pos-1)↑z),t,(¯1+pos+⍴f)↓z ⍝ Do substitution
→Loop ⍝ Until no more
⍝
⍝ Special case, an enclosed of things
⍝
Enclosed: ⍝
z←{⍵ Replace patterns}¨Line ⍝ Do for each
→0
⍝
⍝ Special case, a matrix of hopefully characters
⍝
Matrix: ⍝ Do for each line of the Matrix and reshape
the result
z←((1↑⍴Line),1)⍴{⍵ Replace patterns}¨⊂[2]Line
→0
And some examples:
'foobartestfootest' Replace 'foo' 'xy' 'st' 'ST' 'te' 'et' 'S' 's' 'T' 'x'
xybaretsxxyetsx
(⎕cr 'Replace') Replace 'Loop' 'Boucle' 'Main' 'Principal'
z←Line Replace patterns;f;t;P;pos
⍝
⍝ Check what is effectively `Line`
⍝
→((≡Line)≥2)/Enclosed ⍝ Line is an Enclose of things
→(2=⍴⍴Line)/Matrix ⍝ Line is a Matrix
⍝
⍝ Do the job, single vector source, an even number of changes
⍝
patterns←,¨patterns ⍝ Convert scalar to vector
z←,Line ⍝ I only work on vectors
Principal: →(0=⍴patterns)/0 ⍝ No more replace to do, so done.
(f t)←2↑patterns ⍝ Get the 'from' and 'to'
patterns←2↓patterns ⍝ drop 2 from the list
P←⌽(∧/[1](¯1+⍳⍴f)⌽f∘.=z)/⍳⍴z ⍝ get the pos where string is found, reverse
order
Boucle: →(0=⍴P)/Principal ⍝ Until there is none
pos←1↑P ⍝ get the pos
P←1↓P ⍝ drop from future
z←((pos-1)↑z),t,(¯1+pos+⍴f)↓z ⍝ Do substitution
→Boucle ⍝ Until no more
⍝
⍝ Special case, an enclosed of things
⍝
Enclosed: ⍝
z←{⍵ Replace patterns}¨Line ⍝ Do for each
→0
⍝
⍝ Special case, a matrix of hopefully characters
⍝
Matrix: ⍝ Do for each line of the Matrix and reshape
the result
z←((1↑⍴Line),1)⍴{⍵ Replace patterns}¨⊂[2]Line
→0
Xtian.
On 2016-04-12 06:39, Elias Mårtenson wrote:
I had a need to to replace substrings with a replacement, and I'm having a hard
time coming up with an concise solution. What I need to do is this:
'foobartestfootest' replace 'foo' 'xy'
Should yield:
'xybartestxytest'
Any suggestions?
Regards,
Elias