I've written a dfn in APL to remove leading, trailing and multiple space. Is there any other way to further improve it?
{a←(⍵∊' ') ⋄ b←((¯1↓(a,0)×(1,a))+(⌽∧\(⌽⍵)=' '))=0 ⋄ b/⍵} ' sad as asdasd asd '
o/p sad as asdasd asd
I've written a dfn in APL to remove leading, trailing and multiple space. Is there any other way to further improve it?
{a←(⍵∊' ') ⋄ b←((¯1↓(a,0)×(1,a))+(⌽∧\(⌽⍵)=' '))=0 ⋄ b/⍵} ' sad as asdasd asd '
o/p sad as asdasd asd
Here is a minor rewrite, just to remove parantheses and use boolean operators:
{a←⍵=' ' ⋄ b←~(¯1↓(a,0)∧(1,a))∨(⌽∧\⌽a) ⋄ b/⍵}
As a side-effect, it is also 16% faster ;-)
I'd also recommend to )load dfns
and )ed dxb
to learn from that fn which does the same even faster and also for matrices, nested data etc.
Removing leading spaces:
{(+/×\' '=⍵)↓⍵}
You can remove from the right by reversing the string and run the same code.
Removing multiple spaces:
{(~' '⍷⍵)/⍵}
Remove leading, trailing and multiple space
{(' '=1↑∆)↓(-' '=¯1↑∆)↓∆←(∼' '⍷⍵)/⍵}
it is more efficient this way.