Simple examples: Difference between revisions

From APL Wiki
Jump to navigation Jump to search
Miraheze>Adám Brudzewsky
m (Text replacement - "</code>" to "</source>")
Miraheze>Adám Brudzewsky
m (Text replacement - "<code class="apl">" to "<source lang=apl inline>")
Line 3: Line 3:
APL represents text as character lists (vectors), making many text operations trivial.
APL represents text as character lists (vectors), making many text operations trivial.
=== Indices of multiple elements ===
=== Indices of multiple elements ===
<code class="apl">∊</source> gives us a mask for elements (characters) in the left argument that are members of the right argument:
<source lang=apl inline>∊</source> gives us a mask for elements (characters) in the left argument that are members of the right argument:
<source lang=apl>
<source lang=apl>
       'mississippi'∊'sp'
       'mississippi'∊'sp'
0 0 1 1 0 1 1 0 1 1 0
0 0 1 1 0 1 1 0 1 1 0
</source>
</source>
<code class="apl">⍸</source> gives us the indices where true (1):
<source lang=apl inline>⍸</source> gives us the indices where true (1):
<source lang=apl>
<source lang=apl>
       ⍸'mississippi'∊'sp'
       ⍸'mississippi'∊'sp'

Revision as of 17:43, 30 October 2019

This page contains examples that show APL's strengths. The examples require minimal background and have no special dependencies.

Text processing

APL represents text as character lists (vectors), making many text operations trivial.

Indices of multiple elements

gives us a mask for elements (characters) in the left argument that are members of the right argument:

      'mississippi'∊'sp'
0 0 1 1 0 1 1 0 1 1 0

gives us the indices where true (1):

      ⍸'mississippi'∊'sp'
3 4 6 7 9 10

We can combine this into an anonymous infix (dyadic) function:

      'mississippi' (⍸∊) 'sp'
3 4 6 7 9 10

Parenthesis nesting level

First we compare all characters to the opening and closing characters;

      '()'∘.='plus(square(a),plus(square(b),times(2,plus(a,b)))'
0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1

An opening increases the current level, while a closing decreases, so we convert this to changes (or deltas) by subtracting the bottom row from the top row:

      -⌿'()'∘.='plus(square(a),plus(square(b),times(2,plus(a,b)))'
0 0 0 0 1 0 0 0 0 0 0 1 0 ¯1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 ¯1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 ¯1 ¯1 ¯1

The running sum is what we're looking for:

      +\-⌿'()'∘.='plus(square(a),plus(square(b),times(2,plus(a,b)))'
0 0 0 0 1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 2 2 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 3 2 1
Works in: all APLs

Template:APL programming language