From d626b2d2143f16ab3bd7b491fdd7cb0c99deb6f3 Mon Sep 17 00:00:00 2001 From: crc Date: Tue, 14 Jan 2020 17:47:33 +0000 Subject: [PATCH] add notes on recursion, loop tradeoffs FossilOrigin-Name: 538e18570ef3032f755d92723fc20f532c4bbd8953146d320cd5f870ff3492b3 --- doc/RETRO-Book.md | 17 +++++++++++++++++ doc/book/techniques/loops | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/doc/RETRO-Book.md b/doc/RETRO-Book.md index 07d18d6..e202218 100644 --- a/doc/RETRO-Book.md +++ b/doc/RETRO-Book.md @@ -2460,6 +2460,15 @@ one of these, use `0;`, `-if;` or `if;`. :test #100 repeat dup #50 eq? [ 'done! s:put nl ] if; n:dec again ; test +You can also achieve this via recursion: + + :test 0; dup n:put sp n:dec test ; + #100 test + +Be careful with recursion as the virtual machine will have a limited +amount of space for the address stack and recursing too many times +can cause a stack overflow. + ## Counted Loops There are two combinators for counted loops. These are `times` and @@ -2478,6 +2487,14 @@ The loop indexes can be accessed outside the loop body: :squares [ display ] times nl ; #100 squares +## Tradeoffs + +The unconditional loop form is more efficient as it's just a +simple jump operation. The `times` counted loops are a little +slower, but can be cleaner and more readable in many cases. The +`times` form is significantly slower than the other +two forms. + # Working With Numbers Numbers in RETRO are signed integers. diff --git a/doc/book/techniques/loops b/doc/book/techniques/loops index 1c92434..9cb9396 100644 --- a/doc/book/techniques/loops +++ b/doc/book/techniques/loops @@ -18,6 +18,15 @@ one of these, use `0;`, `-if;` or `if;`. :test #100 repeat dup #50 eq? [ 'done! s:put nl ] if; n:dec again ; test +You can also achieve this via recursion: + + :test 0; dup n:put sp n:dec test ; + #100 test + +Be careful with recursion as the virtual machine will have a limited +amount of space for the address stack and recursing too many times +can cause a stack overflow. + ## Counted Loops There are two combinators for counted loops. These are `times` and @@ -35,3 +44,11 @@ The loop indexes can be accessed outside the loop body: :display I n:square n:put sp ; :squares [ display ] times nl ; #100 squares + +## Tradeoffs + +The unconditional loop form is more efficient as it's just a +simple jump operation. The `times` counted loops are a little +slower, but can be cleaner and more readable in many cases. The +`times` form is significantly slower than the other +two forms.