0

While I believe I have found a sound algorithm for my function (Factorial) I'm very confused as to why it loops infinitely. Here's my code :

declare
fun{Fact N}
   local M=1 in             %I suppose it loops from here??
      local FactT in        %But the function call starts from here
     fun{FactT N Acc}       % which doesn't include the local declaration of M
        if M==N then
           {Browse M}
           Acc
        else
           %{Browse M}     %displays infinite lines of 1s
           %{Browse N}
           %{Browse Acc}   %They form a continuously growing list of 1s
           {FactT (M+1) (M|Acc)}end
     end
     {FactT N nil}
      end
   end
end

{Browse {Fact 3}}
user3078046
  • 31
  • 1
  • 7

2 Answers2

0

I see program written in this language at the first time, but I think I found the problem. Function FactT is recursive, right? First argument of FactT is "upper limit", right? I think the problem is here

{FactT (M+1) (M|Acc)}end

You're comparing M (which is always equals 1) with M+1 (which is passed as the first argument (N)). This comparing is always "false". For example at first iteration it's 1==N (false), at second iteration it is not 2==N, it's 1==2 (false) and so on.

Sorry for bad explanation. I hope you understand what I wanted to say.

Probably it should look like this:

{FactT N ((M+1)|Acc)}end

or something.

Rei
  • 73
  • 5
  • Thank you very much for this explanation. I think you pinpointed where the mistake was. But the suggestion you made can't be applied because the (M+1)|Acc part extends 2 to nil as a list then 2 to 2 and keeps on going. So the arguments don't evolve, which beats the recursion principle. – user3078046 Oct 16 '14 at 14:03
  • @user3078046 as I said, I never saw this language before, so I didn't really know what (M+1)|Acc means ( and didn't want to google it :) ). You're welcome anyway. – Rei Oct 16 '14 at 17:00
0

You never increment M => {Fact (M+1) (M|Acc}} is always {Fact 2 1|Acc}

and to make your code more readable, you're not obilged to write

fun...
   local ...
   in ...
   end
end

you can just write

fun...
   ...
in
   ...
end

code

Taking those things into account, the most simple factorial function is

declare
fun {Fact N}
   fun{Aux N Acc}
      if N=<0 then Acc
      else {Aux N-1 N*Acc}
      end
   end
in
   {Aux N 1}
end
yakoudbz
  • 903
  • 1
  • 6
  • 14
  • Thank you for your suggestion (about the readability) I'll try that in the future. I'm going to try and rewrite the algorithm with a different idea. – user3078046 Oct 16 '14 at 14:07