Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. # invoke as jq -f bf.jq -rS --arg program [PROGRAM] -
  2. # interactivity is not supported
  3.  
  4. # try:
  5. # $ echo "" | jq -f bf.jq -RrS --arg program '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
  6.  
  7. def increment: .tape.head+=1;
  8. def decrement: .tape.head-=1;
  9. def shiftleft:
  10. .tape.left=[.tape.head]+.tape.left |
  11. .tape.head=(.tape.right[0]//0) |
  12. .tape.right|=.[1:];
  13. def shiftright:
  14. .tape.right=[.tape.head]+.tape.right |
  15. .tape.head=(.tape.left[0]//0) |
  16. .tape.left|=.[1:];
  17. def loop(f):
  18. until(.tape.head == 0; f);
  19. def bfin:
  20. .tape.head=(.in[0]//0) |
  21. .in|=.[1:];
  22. def bfout:
  23. .out=.out+[.tape.head];
  24.  
  25. def setup:
  26. {"tape":
  27. {"left":[]
  28. ,"head":0
  29. ,"right":[]
  30. }
  31. ,"in":explode
  32. ,"out":[]
  33. };
  34.  
  35. def finalize: .out|implode;
  36.  
  37. def instrs:
  38. {"+": increment
  39. ,"-": decrement
  40. ,"<": shiftleft
  41. ,">": shiftright
  42. ,",": bfin
  43. ,".": bfout
  44. };
  45.  
  46. # find the index of closing bracket
  47. def findmatch(prog;d;n):
  48. if prog[n:n+1] == "["
  49. then findmatch(prog;d+1;n+1)
  50. elif prog[n:n+1] == "]"
  51. then if d == 0
  52. then n
  53. else findmatch(prog;d-1;n+1)
  54. end
  55. else findmatch(prog;d;n+1)
  56. end;
  57.  
  58. def interpret(prog):
  59. if prog == ""
  60. then .
  61. elif prog[0:1] == "["
  62. then findmatch(prog;0;1) as $loopend | loop(interpret(prog[1:$loopend])) | interpret(prog[$loopend+1:])
  63. else (instrs[(prog[0:1])//.])|interpret(prog[1:])
  64. end;
  65.  
  66. setup|interpret($program)|finalize
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement