Reputation: 3
any tail-recursive version for the below mentioned pseudocode ? Thanks !
(define (min list)
(cond
((null? list) '())
((null? (cdr list)) (car list))
(#t (let ((a (car list))
(b (min (cdr list))))
(if (< b a) b a)))))
Upvotes: 0
Views: 1310
Reputation: 27164
(define (min list)
(min-helper list #f))
(define (min-helper list min-so-far)
(if (null? list)
min-so-far
(let ((m (car list)))
(if (eq? min-so-far #f)
(set! min-so-far m))
(if (< m min-so-far)
(min-helper (cdr list) m)
(min-helper (cdr list) min-so-far)))))
Upvotes: 0
Reputation: 1
(define (min ns)
(let loop ( (ns-left ns) (min-so-far maxint) )
(if (null? ns-left)
min-so-far
(loop
(cdr ns-left)
(if (< (car ns-left) min-so-far)
(car ns-left)
min-so-far )))))
Upvotes: 0
Reputation: 9714
(define (min list)
(let imin ((l (cdr list))
(m (car list)))
(cond
((null? l) m)
(else
(let ((a (car l)))
(imin (cdr l)
(if (< a m) a m)))))))
Upvotes: 1
Reputation: 370102
Define a helper function that takes a list and the smallest element found so far (let's call it b). If the list is empty, it should return b, otherwise if the head of the list (a) is smaller than b than it should return (helper (cdr list) a)
, otherwise (helper (cdr list) b)
. Now we can define (min list)
as (helper (cdr list) (car list))
.
Upvotes: 1