The following warnings occurred:
Warning [2] count(): Parameter must be an array or an object that implements Countable - Line: 795 - File: showthread.php PHP 7.4.33 (FreeBSD)
File Line Function
/showthread.php 795 errorHandler->error





Post Reply 
[Programming] Proper Tail Recursion - Bypass recursion limit
03-27-2023, 08:37 PM (This post was last modified: 03-28-2023 08:16 AM by FernandoMorea.)
Post: #1
[Programming] Proper Tail Recursion - Bypass recursion limit
My research on how to bypass hp prime's recursion limit, coupled with my studies of lisp and haskell, led me to this solution: saving the continuation of a function in a variable, that will be returned to the user, the user must re-run the result to iterate the process.
To cheat the static analysis of the CAS that triggers the recursion limit, we must also define a fake function that simply calls back the main function.

The function must be tail recursive:
Let's recall what a tail recursive function looks like, let's take the factorial and python as toy language:
Code:

def factorial(n, a):
  if n < 0:
    return 0
  elif n == 0:
    return 1
  elif n == 1:
    return a
  else:
    return factorial(n - 1, n * a)

So now let's go to our HP PRIME:
Code:

#cas
self_fact:= 
cont:= QUOTE(myfact(arg0,arg1));

myfact(x,curr):= 
IF x≤0
THEN curr
ELSE
arg0:=x-1; 
arg1:=x*curr; 
cont:= QUOTE(self_fact);
{'cont',arg1};
END;

#end

Another example could be the algorith for Polynomial long division

Code:

#cas
long(a,b):=
BEGIN
LOCAL t;
t:= [a(1)/b(1), a-(a(1)/b(1))*b];
tempa:= tail(t(2));
tempb:= b;
cont:=QUOTE(self_long);
{'cont', t};
END;

self_long:=
cont:=QUOTE(long(tempa,tempb));
#end
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
[Programming] Proper Tail Recursion - Bypass recursion limit - FernandoMorea - 03-27-2023 08:37 PM



User(s) browsing this thread: 1 Guest(s)