Paste: bttr.k

Author: razetime
Mode: text
Date: Thu, 9 Feb 2023 17:03:21
Plain Text |
/
apl interpreter in k
by razetime, 2022, 2023.
\

/ utility
/ - str&unicode
uni:  (256!0x0080c0e0f0)'256!
unich:{{@[x;&1=#'x;*:]}(&-65<x)_x}
idg:{(1=#x)&&/(x>"/")&(x<":")} / is digit?
ial:{&/((x<"[")&(x>"@"))|(x<"{")&x>"`"} / is alpha?
/ - Error (probably for later use.)
err:{[msg; idx; tok] `0: msg,"error at index ",($idx),"Token: ",tok; `exit[]}

/ Tokenizing Utilities
rq: {x|1_x,0}
/ always update toks and syms together.
toks:  unich"(){}[]'0123456789¯abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
syms:  `lp`rp`lb`rb`ls`rs`str,(11#`num),(52#`nam)
toks,: unich"⋄←→⍝⍺⍵⎕∇⍞⍬∘⍀⌿\\/⍨¨⌶⍤⌸⍥⍠⌺@⍣+-*÷<≤=≥>≠∨∧×?∊⍴~↑↓⍳○*⊢⌈⌊⍎⍕⊂⊃∩∪⊥⊤|⌹⍒⍋⌽⍉⊖⍟⍱⍲!⍷⍸⊣⌷≡≢⊆⊇⍪"
syms,: `sep`ass`got``lar`rar`qua`rec`eio`zil`jot,(4#`fop),(10#`pop),53#`pfn
mt:("",/:toks)!syms
/ token alignment check
/ `0:toks{x," ",$y}'syms;
/ syms that take more than one char:
/ str,num,name,cmt,quad,jot
str:{{x+"'"~y x}[;y]{~"'"~y x}[;y]{x+1+2*"''"~y x+1+!2}[;y]/x+"'"~y x}
num:{
  d:{idg y x}[;y](1+)/
  d x+"."~y x:d x+"¯"~y x}
cmt:{{(~"\n"~y x)&x<#y}[;y]{x+1}/x}
nam:{{(idg y x)|(ial y x)|x~"_"}[;y](1+)/{(ial y x)|x~"_"}[;y](1+)/x}
jot:{x+2*"."~y x+1}
wsp:{{|/(" ";"\t")~\:y x}[;y](1+)/x}

/ tokenizer
/ tokens are (index;type;data)
tokens:{
  p:unich x
  sls:{(*x)<#y}[;p]{ / take current index, return next index, type
    c:y i:*x
    type:mt"",y i
    next:$["⍝"~c;cmt[i;y]
      "∘"~c;$["."~y i+1;[type:`pop;];]
      "'"~c;str[i;y]
      ("¯"~c)|idg c;num[i;y]
      (b:"⎕"~c)|ial c;nam[i+b;y]
      |/(" ";"\t")~\:c;wsp[i;y]
      i+1]
    (next; type)}[;p]\0
  {~^x[;1]}# -1_(1_sls,`),','(*'sls)_p}

/ runner utilities:
isa:{|/`num`str`arr=x} / is an array?
/ arrays are (`arr;length;data).
gv:{`arr,$[`str=x;(-2+#y;1_-1_y);`num=x;((),.y)]} / get value of constant.

/ run a reversed stream of tokens with an environment.
/ (index;env;exec_stack;tokens) 
run:{x[0]<#x[3]}{[x]
  (x;y;z;u):x
   \(i;t;d):u x
  / $[isa t; $[ z~();z:,,gv[t;d];0];0]
    /`arr=*z;[z[0;1]:$[z[0;1]~();2;z[0;1]+1]
    / z[0;2]:z[0;2],,gv[t;d]]]]
    \x
  (x+1;y;z;u)
}/
/ run (0;()!();();tokens "3 3 3")

New Annotation

Summary:
Author:
Mode:
Body: