recursion - Common Lisp: Using (let) for evaluating recursive function -
so wrote returns maximal subset sum given list of positive integers. however, use (let) make code more efficient. know if or how possible.
(defun subset-sum1 (numbers capacity) (subset-sum numbers capacity 0)) (defun subset-sum (numbers capacity counter) (cond ((null numbers) counter) ((= counter capacity) counter) ;; return if counter 'hits' capacity ((< capacity (+ (car numbers) counter)) (subset-sum (cdr numbers) capacity counter)) ;; cdr if car branch exceeds capacity ((<= (subset-sum (cdr numbers) capacity counter) (subset-sum (cdr numbers) capacity (+ (car numbers) counter))) (subset-sum (cdr numbers) capacity (+ (car numbers) counter))) ;; choose car (t (subset-sum (cdr numbers) capacity counter)))) ;; choose cdr
the above code works fine in common lisp. but, below, because feel using let make code better. wrote goes infinite loop :( assignment introductory ai class... out novice please!
(defun subset-sum (numbers capacity counter) (let ((exclude (subset-sum (cdr numbers) capacity counter)) (include (subset-sum (cdr numbers) capacity (+ (car numbers) counter)))) (cond ((null numbers) counter) ((= counter capacity) counter) ((< capacity (+ (car numbers) counter)) exclude) ((<= exclude include) include) (t (exclude)))))
you infinite loop because of these lines:
(defun subset-sum (numbers capacity counter) (let ((exclude (subset-sum (cdr numbers) capacity counter))
you keep calling subset-sum recursively, , never terminates. when end of list, , numbers (), keep going, because (cdr '()) '(). handled in original checking (null numbers) (though might more idiomatic use (endp numbers)). can like:
(defun subset-sum (numbers capacity counter) (if (endp numbers) counter (let ((exclude (subset-sum (cdr numbers) capacity counter)) ;... ) (cond ; ... ))))
Comments
Post a Comment