views:

139

answers:

5

Hi guys, 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)))))
+1  A: 

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)).

sepp2k
+2  A: 

You should read up on the fold higher-order functions.

Aidan Cully
In Scheme, `fold` is provided with SRFI 1 (http://srfi.schemers.org/srfi-1/srfi-1.html). If you're using PLT, say `(require srfi/1)`. If using Guile, say `(use-modules (srfi srfi-1))`. For other implementations, read their respective manual. :-)
Chris Jester-Young
+1  A: 
 (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)))))))
SK-logic
A: 
(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 )))))
George Kangas
A: 
(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)))))
Vijay Mathew