Skip to content

Instantly share code, notes, and snippets.

@rdm
Created February 4, 2023 15:10
Show Gist options
  • Save rdm/09072ed7dc3c3ea4b863f6002a31cfb8 to your computer and use it in GitHub Desktop.
Save rdm/09072ed7dc3c3ea4b863f6002a31cfb8 to your computer and use it in GitHub Desktop.
"Thinking in states" using slightly more idomatic J
NB. a rephrase of the J implementation at https://www.metalevel.at/tist/
instrs=: 9 33 1 1 2 1 4 1 3 0 2 1 12 30 3 1 3 0 7 4 1 3 0 2 1 6 4 0 9 8 3 1 15 2 4 13 2 14 0
st=: 0 {:: ]
is=: 1 {:: ]
pc=: 2 {:: ]
fp=: 3 {:: ]
next=: (>:&pc { is)
print=: (1!:2)&2
adv=: (2}.st); is; (2+pc); (fp-2:)
jmp=: (2}.st); is; next; (fp-2:)
i1=: ((next # 0:),st); is; (2+pc); (next+fp)
i2=: (next,st); is; (2+pc); 1+fp
i3=: (((fp-next) { st),st); is; (2+pc); 1+fp
i4=: (1 }. (fp-next) {.@]`[`]} st); is; (2+pc); fp-1:
i5=: (+/@(1 0 { ]),2}.])@st; is; (1+pc); fp-1:
i6=: (-/@(1 0 { ]),2}.])@st; is; (1+pc); fp-1:
i7=: (*/@(1 0 { ]),2}.])@st; is; (1+pc); fp-1:
i8=: (<.@%/@(1 0 { ]),2}.])@st; is; (1+pc); fp-1:
i9=: st; is; next; fp
i10=: adv`jmp@.([: ~:/ 1 0 { st)
i11=: adv`jmp@.([: >:/ 1 0 { st)
i12=: adv`jmp@.([: <:/ 1 0 { st)
i13=: ({.&st, fp, (2+pc), }.@st); is; next; 0:
i14=: print@{.@st ] }.@st; is; (1+pc); fp-1:
i15=: ({.@st, (3+fp), }.@st); is; ((2+fp){st); (>:@fp { st)
step=: ]`i1`i2`i3`i4`i5`i6`i7`i8`i9`i10`i11`i12`i13`i14`i15@.(pc{is)
state0=: ($0); instrs; 0; 0
step^:_ state0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment