CTM: Exercise 3-4

Posted by Urban Hafner Sun, 11 Sep 2005 17:34:59 GMT

The problem

Iterative factorial. This chapter gives a definition of factorial whose maximum stack depth is proportional to the input argument. Give another definition of factorial which results in an iterative computation. Use the techniques of state transformations from an initial state, as shown in the IterLength example.

My solution


  fun {IterFact N}
     fun {IterFact2 N S}
        if N==0 then S
        elseif N>0 then {IterFact2 N-1 S*N}
        else raise domainError(N) end
        end
     end
  in
     {IterFact2 N 1}
  end

Tags , , , ,

Comments are disabled