Search

mercredi 8 février 2017

Self-interpreter: while and loop (7)

Context

As a reminder, here is the final memory map
0 0 0 {instrs} 0 inst_ptr 0 0 0 inactive_flag direction_flag memory_ptr  0 0 0 0 0 {mem}
Let's now see how to implement '[' and ']'

Initial state

  • Memory: see above
  • Cursor: on instruction, next to inst_ptr
  • Input: any

Process

  • Common part 
    • Access memory value - see previous post
    • Copy memory value
    • Move array back to initial position
  •  While '['
    • If copy is null
      • increase inactive_flag
    • If not: do nothing
  • Loop ']'
    • If copy is null: do nothing
    • If not:
      • decrease inactive_flag
      • Set direction_flag to 1

Code for while

Access memory cell
>>>>[->+>+<<]>>[-<<+>>]<+[->>>>[>>]+>>[-]>[-<<+>>]<<<[<<]<<
]
>>>>[>>]<
copy value
[->>+<<]>>[-<<+<[<<]<<+>>>>[>>]>]<<

move array back to initial position
<[[->>+<<]>[->>+<<]<<<]

check current memory value: do nothing if not null and move to corresponding loop otherwise
<+<[>-<[-]]>[-<
  if null (current position: next to memory_pointer)
  increase inactive_flag
  <<<+>>>
>]<
<<<<<

Code for loop

duplicate memory pointer and move to copy
>>>>[->+>+<<]>>[-<<+>>]<+
[
  -
  go to next memory cell
  >>>>[>>]+>>
  (re)init/copy memory indicator
  [-]>[-<<+>>]<<<[<<]<<
]
go to current memory cell
>>>>[>>]<
copy value
[->>+<<]>>[-<<+<[<<]<<+>>>>[>>]>]<<
move array back to initial position
<[[->>+<<]>[->>+<<]<<<]
check current memory value: do nothing if null and move to corresponding while otherwise
<<
[
  if not null (current position: next to memory_pointer)
  reset value
  [-]
  decrease inactive_flag and change direction_flag
  <<<->[-]+>>
]
<<<<<

Final state

  • Memory: see above
  • Cursor: on instruction, next to inst_ptr
  • Input: unchanged
  • Output: unchanged

Aucun commentaire:

Enregistrer un commentaire