#lang racket ; find position of max in a list ; helper function simply passes along all the state that is needed for ; the computation. ; note the tail recursion, so the stack is never more than constant size ; Pre: L is a non-empty list of numbers ; Post: returns position of first maximum in list, 0-origin indexing (define lmax-index (lambda (L) (lmax-index-r (first L) 0 1 (rest L) ) ) ) ; lmax-index recursor ; cur-max - value of the current maximum ; cur-index - position of the current maximum ; L-index - position of the first element of the remaining list ; L - remaining list of numbers to be processed (define lmax-index-r ( lambda (cur-max cur-index L-index L) (if (null? L) cur-index (if (>= cur-max (first L)) ; max still good (it is at least as big as the first element) (lmax-index-r cur-max cur-index (+ 1 L-index) (rest L)) ; first is new max (lmax-index-r (first L) L-index (+ 1 L-index) (rest L)) ) ) ) ) (lmax-index '(1 2 3 4)) ; NOTE: what happens if the >= test above is changed to a > test? ; Now create a function that returns a list of the positions of ; all the maximums in L. ; This would work for an empty list, since the list of positions ; would be empty