Skip to content

Instantly share code, notes, and snippets.

@abrudz
Last active September 13, 2018 16:36
Show Gist options
  • Save abrudz/bd625167e92a6676b096668b08a165fe to your computer and use it in GitHub Desktop.
Save abrudz/bd625167e92a6676b096668b08a165fe to your computer and use it in GitHub Desktop.
cmp with Over operator
cmp←{ ⍝ compare basic arrays, results in ¯1 (⍺ precedes ⍵), 0 (⍺ is identical to ⍵), or 1 (⍺ follows ⍵)
⍝ DEFINITION:
⍝ ┌
⍝ │ ¯1 if ⍺ strictly precedes ⍵
⍝ ⍺ cmp ⍵ = │ 0 if ⍺ exactly matches ⍵
⍝ │ 1 if ⍺ strictly follows ⍵
⍝ └
⍝ AXIOMS:
⍝ 1. exact comparisons, ⎕UCS for characters
⍝ 2. result is first non-zero in ravel order
⍝ 3. complex numbers have imaginary part as additional dimension after real part
⍝ 4. numbers precede characters
⍝ 5. dictionary order: "nothing precedes something", break ties by comparing shape
⍝ 6. visual fidelity: extend with leading 1-axes, break ties by comparing rank
Ö←{(⍵⍵ ⍺)⍺⍺(⍵⍵ ⍵)} ⍝ Over operator
⎕CT←⎕DCT←0 ⋄ ⎕FR←1287 ⍝ Axiom 1: exact or as exact as possible
⍺{11::0 ⋄ ⍺≡⍵}⍵:0 ⍝ Definition: exact match (trap DECF vs xomplex)
⍺>Ö(0∊⍴)⍵:¯1 ⍝ Axiom 5: nothing before something
⍺<Ö(0∊⍴)⍵:1 ⍝ something after nothing
⍺≢Ö(⍴⍴)⍵:c+(⍺ ∇ Ö(⍴⍴)⍵)×0=c←⍺ ∇ Ö(⊢⍴⍨⍴,⍨1⍴⍨r-(⍴⍴))⍵⊣r←⍺⌈Ö(⍴⍴)⍵ ⍝ Axiom 6: extend rank, compare, tie-break by rank
⍺≢Ö⍴⍵:c+(⍺ ∇ Ö(⌽⍴)⍵)×0=c←(⍺ ∇ Ö(m∘↑)⍵)⊣m←⍺⌊Ö⍴⍵ ⍝ Axiom 5: chop shape, compare, tie-break by shape
t←⍺,Ö{(326≠t)×2-2|t←⎕DR ⍵}⍵ ⍝ Axiom 4: 1=num; 2=char; 0=other
1 2≡t:¯1 ⍝ num vs char
2 1≡t:1 ⍝ char vs num
1 1≡t:⊃0~⍨,⍺(>-<)Ö(9 11∘○⍤1 0)⍵ ⍝ Axioms 3 & 2: first nonzero value of num vs num with catenated Zs
2 2≡t:⊃0~⍨,⍺(>-<)Ö ⎕UCS ⍵ ⍝ Axioms 1 & 2: first nonzero value of char vs char using ⎕UCS
|c←⍺ ∇ Ö⊃⍵:c ⋄ ⍺ ∇ Ö(1↓,)⍵ ⍝ Axiom 2: first non-zero in ravel order (for non-simple arrays)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment