Simple examples: Difference between revisions
Miraheze>Adám Brudzewsky |
Miraheze>Adám Brudzewsky No edit summary |
||
Line 4: | Line 4: | ||
* [[Ranking poker hands]] | * [[Ranking poker hands]] | ||
* [[APL Wiki logo]] | |||
==Text processing== | ==Text processing== |
Revision as of 01:47, 3 November 2019
This page contains examples that show APL's strengths. The examples require minimal background and have no special dependencies.
More involved examples include:
Text processing
APL represents text as character lists (vectors), making many text operations trivial.
Split text by delimiter
≠
gives 1 for true and 0 for false. It pairs up a single element argument with all the elements of the other arguments:
','≠'comma,delimited,text' 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1
⊢
returns its right argument:
','⊢'comma,delimited,text' comma,delimited,text
⊆
returns a list of runs as indicated by runs of 1s, leaving out elements indicated by 0s:
1 1 0 1 1 1⊆'Hello!' ┌──┬───┐ │He│lo!│ └──┴───┘
We use the comparison vector to partition the right argument:
','(≠⊆⊢)'comma,delimited,text' ┌─────┬─────────┬────┐ │comma│delimited│text│ └─────┴─────────┴────┘
Notice of you can read the tacit function ≠⊆⊢
like an English sentence: The inequality partitions the right argument.
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