On 09/30/2010 06:57 AM, Peter Breitsprecher wrote:
Well your getting into commands I haven't learnt yet


the only one i can see in my code that is not in yours is local, which i assume is about the first construct you've learned. then, it's easy to avoid local (but that's what you do in your code anyway, just using syntactic sugar to avoid typing it).

just to play with the idea, here's a different version, using an internal helper procedure instead of a function:

declare
fun {Factorial N}
    if N==0
    then [1]
    else
        proc {Factorial I Tail Last}
            if I>N
            then Tail=nil
            else NewTail NewLast=I*Last in
                Tail=NewLast|NewTail
                {Factorial I+1 NewTail NewLast} end end
        Tail Head=1|Tail in
        {Factorial 1 Tail 1}
        Head end end

{Browse {Factorial 5}}
% [1 1 2 6 24 120]

what may be new to you is extending the list kind of left to right by exploiting unbound variables (a very cool feature of oz).


, or maybe the professor hasn't taught them to us yet. I sort of understand how your piece of software works. Given my original problem, can you look at this and see if it would be deemed acceptable?

obviously, i can't tell how your tutor will judge things.



declare
fun {FactLoop I N Acc}
    if I==N+1

I>N might be better.


    then Acc
    elseif
       I==1 then {FactLoop I+1 N Acc}
    else {FactLoop I+1 N I*Acc.1|Acc}
    end
end
fun {Reverse Xs}
   case Xs of nil then nil
   [] X|Xr then
      {Append {Reverse Xr} [X]}
   end
end
fun {Fact N}
    {FactLoop 1 N [1]}
end
fun {Fact1 N}
   {Reverse {FactLoop 1 N [1]}}
end

{Browse {Fact 4}} %%Tail Recursive with output same as example [24 6 2 1]
{Browse {Fact1 4}}%%Tail Recursive with output reversed [1 2 6 24]

Technically it answers the question, but would it be deemed correct?

perhaps make it work with N=0, depending on the specs of your task.

one issue here is complexity. your code is O(n), but the version with increasing values in the output (Fact1) runs in O(n^2) time due to the repetitive traversals of the list in Reverse/Append. the code above, using unbound variables, runs in O(n) time. it corresponds to an implementation of a linked list in, e.g., c where you have a pointer to both the first and the last element on the list, hence you can grow the list at the right end in constant time.
you'll likely see this pattern in difference lists later in the course.

vQ
_________________________________________________________________________________
mozart-users mailing list                               
[email protected]
http://www.mozart-oz.org/mailman/listinfo/mozart-users

Reply via email to