Dear Peter, It is indeed possible to turn the factorial list function into a tail recursive one.
Think about how to build the list with an accumulator, such that the final result is the last value of the accumulator. Each element of the list depends on the element that comes next, therefore you should build the list from right to left. Successive values of the accumulator should be: [1] [2 1] = 2|[1] [6 2 1] = 6|[2 1] [24 6 2 1] = 24|[6 2 1] Consider you loop over an index going from 1 to N, and you should be able to write a tail recursive function that uses the accumulator as I described above, and returns the expected list at the end. Good luck :-) Raphael On Wed, Sep 29, 2010 at 6:44 PM, Peter Breitsprecher <[email protected]>wrote: > Ok I admit It I am stumped. I know I'm new to this Language, but I'm > trying and want to learn. We were given this code. > > fun {Fact N} > if N==1 then [N] > else > Out={Fact N-1} > in > N*Out.1|Out > end > end > > Example of execution: {Fact 4} -> [24 6 2 1] > > He asked if this program is tail recursive, which it is not, because the > recursion needs to be the last operation, and in this case the last > operation is the N*Out.1. > > So I wrote these two pieces of code. > > This one you need to pass the Accumulator to in the function call > > fun {Fact N Acc} > if N==1 then Acc > else > {Fact N-1 N*Acc} > end > end > > And this one that uses another function to loop. > > fun {Fact N} > fun {FactLoop N Acc} > if N == 0 then Acc > else > {FactLoop N-1 N*Acc} > end > end > in > {FactLoop N 1} > end > > Now my problem is that I get the end result of 24 with these programs, but > I can't get them to display a list like in the example the professor gave > us. > > How do I change my code, or make the Professor code so that it is tail > recursive and still produce a list. In Part B of the question it is to > order the list of factorials from smallest to largest, which I have finished > using his code, but not tail recursive. > > Also, can someone please tell me how to reply to these threads? I am > submitting my responses Via Email, but they don't seem to end up here. > > Thank you for your help. > > > > -- > Kurt Breitsprecher > (807) 474-9601 > [email protected] > > > > _________________________________________________________________________________ > mozart-users mailing list > [email protected] > http://www.mozart-oz.org/mailman/listinfo/mozart-users >
_________________________________________________________________________________ mozart-users mailing list [email protected] http://www.mozart-oz.org/mailman/listinfo/mozart-users
