Search

Affichage des articles dont le libellé est then. Afficher tous les articles
Affichage des articles dont le libellé est then. Afficher tous les articles

mercredi 8 février 2017

Condtional execution: if / then / else

Context

Let's see how we can execute some code if a condition (already evaluated) is true ( <> 0) or some other code if false (=0). A best practice would be to end up at the same cursor position for both cases.
There are multiple ways to implement such behavior, one is: set an 'else' bit to true, execute some code if condition is true, using the details mentionnes on this previous post, that would also reset condition and else bit; move to else bit and execute some code if else is still true (so, if condition was false) and reset else bit.
Initial state
  • Memory: A, 0
  • Cursor: first cell
  • Input: any

Process

  • Set second cell to 1
  • While first cell is not null
    • Do something
    • Reset first cell
    • Reset second cell
  • While second cell is not null
    • Do something else
    • Reset second cell
  • Go back to first cell (optional)

Code 

>+<[ do something [-]>-<]>[ do something else -]<

Final state

  • Memory: 0, 0
  • Cursor: first cell
  • Input: any
  • Output: unchanged

Note: another option would be to have a different cursor position during else execution between the two cases
>+<[ do something [-]>-]>[ do something else ->]<<
Here
  • if condition is true, then cursor is on third cell while else is executed
  • if condition is false, then cursor is on second cell while else is executed
But in all cases, cursor ends up at the same position.

Conditional execution: if / then

Context

Assuming that a condition has been already evaluated (0 = false, true otherwise), it's fairly simple to execute code based on this condition. However, condition also need to be reset after execution of conditional code, to make sure that loop breaks and that both true and false cases ends up to the same state.
Finally, note that the conditional execution implemented like this destroys the condition, for the reason mentioned above.

Initial state

  • Memory: A
  • Cursor: first cell
  • Input: any

Process

  • While first cell is not null
    • Do something
    • Reset first cell

Code 

[do something[-]]

Final state



  • Memory: 0
  • Cursor: first cell
  • Input: any
  • Output: unchanged