0

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
user3263192
  • 499
  • 1
  • 4
  • 14

3 Answers3

1

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.

MBaas
  • 7,248
  • 6
  • 44
  • 61
1

Removing leading spaces:

{(+/×\' '=⍵)↓⍵}

You can remove from the right by reversing the string and run the same code.

Removing multiple spaces:

{(~'  '⍷⍵)/⍵}
Elias Mårtenson
  • 3,820
  • 23
  • 32
0

Remove leading, trailing and multiple space

{(' '=1↑∆)↓(-' '=¯1↑∆)↓∆←(∼'  '⍷⍵)/⍵}

it is more efficient this way.

StackPC
  • 36
  • 2