Tuesday, March 4, 2014

Scheme Tail Recursion

(define (listlen2);I am lazy so i made a built in list for testing
  (listlen1 (list 1 2 3 4 5)))
(define (listlen1 tlist);procedure listlen without the need to define starting count
  (listlen tlist 0))
(define (listlen tlist count)
           (if (null? tlist);check if reached end of list
             count;write count if reached end
             (listlen (cdr tlist) (+ 1 count))));recurse with remainder of list and increment count
 
(define (trprod2);I am lazy so i made a built in list for testing
  (trprod1 (list 1 2 3 4 5)))
(define (trprod1 tlist);procedure tprod without need to define start prod
  (trprod tlist 1))
(define (trprod tlist prod)
  (if (null? tlist);check is reached end of list
      prod;write prod if reached end
      (trprod (cdr tlist) (* (car tlist) prod))));recurse with remainder of list and product of car and current product

**************************************************************
> (listlen2)
5
> (listlen1 (list 1 2 3 4 5 6 7 8 9))
9
> (trprod2)
120
> (trprod1 (list 1 2 3))
6
>


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.