taskGNU Common Lisp - Tasks: task #788, tail recursive differs from...

 
 

You are not allowed to post comments on this tracker with your current authentication level.

task #788: tail recursive differs from iteration

Submitter:  Camm Maguire <camm>
Submitted:  -
   
 
Category:  Bugs Should Start On:  Thu 21 Mar 2002 12:00:00 AM UTC
Should be Finished on:  Thu 21 Mar 2002 12:00:00 AM UTC Priority:  5 - Normal
Status:  None Privacy:  Public
Assigned to:  None Percent Complete:  0%
Open/Closed:  Closed Effort:  96.00

Fri 20 Sep 2002 07:04:11 PM UTC, comment #1: 

Common Lisp does not guarantee that tail call optimizaitons will be performed.

Paul F. Dietz <pfdietz>
Group Member
-, original submission:  


> Example of iterative vs tail-recursive code.  The former works in
> GCL 2.4.0, the latter slags with a invocation history stack overflow.
>
> ;;; do modular exponentiation - get (B**E) mod M.
>
> ;;; general driver
> (defun expmod (base exponent modulus)
>   (expmod-iter base exponent modulus))
>
> ;;; iterative algorithm (aye, matey, this be bletcherous)
> (defun expmod-iter (x b n)
>   (let ((z 1)
> (b b)
> (x x))
>     (loop
>      (when (= b 0) (return z))
>      (loop
>       (when (not (= (rem b 2) 0)) (return))
>       (setf b (/ b 2))
>       (setf x (rem (* x x) n)))
>      (setf b (- b 1))
>      (setf z (rem (* z x) n)))))
>
>
> ;;; tail-recursive algorithm from SICP
> (defun expmod-rec (base exponent modulus)
>   (cond ((= exponent 0) 1)
> ((evenp exponent)
> (rem (square (expmod base (floor (/ exponent 2)) modulus))
>       modulus))
>         (t
> (rem (* base (expmod base (- exponent 1) modulus))
>       modulus))))
>
> (defun square(x) (* x x))
>
>

Camm Maguire <camm>
Group administrator

 

(Note: upload size limit is set to 16384 kB, after insertion of the required escape characters.)

No files currently attached

 

Depends on the following items: None found

Items that depend on this one: None found

 

Carbon-Copy List
  • -email is unavailable- added by camm (Updated the item)
  •  

    There are 0 votes so far. Votes easily highlight which items people would like to see resolved in priority, independently of the priority of the item set by tracker managers.

     

    Follow 2 latest changes.

    Date Changed by Updated Field Previous Value => Replaced by
    2013-11-21 camm Percent CompleteNone 0%
        Open/ClosedOpen Closed

    Back to the top

    Powered by Savane 3.14-04e1.
    Corresponding source code