LearnBuild toward a chatbotMoving and copying
Moving and copying
Aim. At the end of this lesson you can use a number in a sum and still have it afterwards.
Where the lessons are going
The sum uses each number more than once, so a program has to read a number without losing it. This lesson adds that: moving a number, copying it, and feeding several cells in one pass.
Move a number
Try it: the left cell holds 4. Press Step until the program has ended, and watch where the 4 goes:
What you just saw
The 4 arrived in the right cell, and the left cell is empty.
The loop had to know when to stop. Its only question is "is this cell zero?" (step 4 of lesson 1), so it counted the left cell down to zero. In brainfuck, looking at a number and using it up are the same thing.
Copy a number
To keep a number, a program pours it into two cells at once and then pours one of those back. Choose the number to copy and watch the third cell: press Play, or drag Step back and forth:
The helper in the third cell filled up and emptied again, and the number ended in two places. The first loop poured the number into the copy and the helper at once, and emptied the original. The second loop poured the helper back into the original. Such a helper is called a scratch cell: empty before, empty after. The chat program is full of them. The slider stops at 9; the real program copies numbers up to 4,294,967,295 the same way.
Try it: this is the same program with the number 3. Press Step until the program has ended, and keep an eye on the third cell:
What you just saw
Original 3, copy 3, and the helper empty again: the number stands in two places. A program that wants to keep a number it reads always does this, because the read destroys it and the helper makes up for it.
Fill two cells in one go
Try it: this is the copy program of step 2. Change it so that cell 0, cell 1 and cell 2 all hold the 5 at the end. Cell 3 is your scratch cell and must end empty:
Hint 1
The first loop pours into cell 1 and cell 2. Let it pour into cell 3 as well: one more >+, and one more < to walk back.
Hint 2
The helper is now cell 3, three cells away. So the second loop becomes >>>[-<<<+>>>].
What you just saw
One loop can feed as many cells as you like in one pass. Your program was also tried with a 9 in place of the 5, to make sure it copies and does not count.
This matters for a model: one number goes into many sums, and with one pass it is poured into all of them at once.
What you can do now
Read a number and keep it, and feed several cells in one pass. The 90 the sum starts with can now be used and still be there for the next product.
What comes back later
The pass of step 3 that feeds several cells is the building block almost everything in the chat program is made of. Step 3 of lesson 3 shows why it is cheap.
Scratch cells have a price: they take room on the tape, next to the data. The rounding of step 5 of lesson 5 needs ten of them.