From 6fc314b5a0ccc2bb4c351497734dbda0c7c5bfb7 Mon Sep 17 00:00:00 2001 From: neauoire Date: Tue, 6 Jun 2023 11:49:28 -0700 Subject: [PATCH] (fib.tal) Added tail-recursive version --- projects/examples/exercises/fib.tal | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/projects/examples/exercises/fib.tal b/projects/examples/exercises/fib.tal index f26ef59..7a98d5d 100644 --- a/projects/examples/exercises/fib.tal +++ b/projects/examples/exercises/fib.tal @@ -1,5 +1,5 @@ ( Fibonacci: - A series of numbers where the next number + A series of numbers where the next number is made of the two numbers before it ) |100 @@ -7,13 +7,16 @@ #0019 #0000 &l DUP2 pdec #2018 DEO - DUP2 fib pdec #0a18 DEO + DUP2 fib pdec #2018 DEO + DUP2 #0000 #0001 ROT2 fibr pdec #0a18 DEO POP2 POP2 INC2 GTH2k ?&l POP2 POP2 #010f DEO BRK +( recursive ) + @fib ( num -- numfib* ) #0001 GTH2k ?&ok POP2 JMP2r &ok @@ -22,6 +25,19 @@ BRK ADD2 JMP2r +( tail-recursive ) + +@fibr ( a* b* num* -- a* b* num* ) + ORAk ?&no-0 + POP2 OVR2 JMP2r &no-0 + DUP2 #0001 NEQ2 ?&no-1 + POP2 DUP2 JMP2r &no-1 + #0001 SUB2 STH2 + SWP2 ADD2k NIP2 STH2r +!fibr + +( print routine ) + @pdec ( short* -- ) #2710 LIT2r 00fb