Take the 2-minute tour ×

I am a beginner in scheme and I want to know how you find the location of an element in a list. For example, in this given list,

(list 1 2 13)

I found the maximum using accumulative recursion, but I need to also find the location of the maximum, so if the function is:

(max-with-location (list 1 2 13)), I need to get: (list 13 (list 3))

Please help me out.

share|improve this question
add comment

5 Answers

This sounds like homework, and if this is the case then any of these solutions won't help. What you're likely expected to do is to revise the code that you wrote to find the maximum: instead of a single accumulator input to the loop, add one more for the position of the maximum-so-far. That will not be too hard given that you already have implemented max.

share|improve this answer
add comment

I don't use Scheme, but in CL it's (position 13 (list 1 2 13))

Maybe it's the same...

So for your code, you'd want something like this:

(list (max (list 1 2 13)) (position (max (list 1 2 13)))

which would return (13 2)

edit: max is supposed to be your max algorithm, though I imagine there might already be a function for this

double edit: if that still doesn't work, you could always use a counter that increments each time through your recursive function, then return that as well...

share|improve this answer
add comment

Use list-ref like so:

(define tlist '(a b c d))

(list-ref tlist 2)

>> c
share|improve this answer
That returns the item given the position, I believe he needs the reverse... –  Jeff May 28 '11 at 18:05
ah - right. Looks like I misunderstood the question. –  Shaun May 28 '11 at 18:12
add comment

first you have to determinate the max number:

(define max_list1
    (lambda (l)
        ((empty? (rest l)) l)
        (else (max_aux_list (first l) (rest l))))))

(define (max_aux_list n lista)
    ((empty? lista) n)
    ((> n (first lista)) (max_aux_list n (rest lista)))
    (else (max_aux_list (first lista) (rest lista)))))

then you have to count the position number of an element.

(define find_in_position
  (lambda (n lista)
      ((empty? lista) 0)
      ((= n (first lista)) 1)
      (else (+ 1 (find_in_position n (rest lista)))))))

finally, list both resoults.

(define (the_max_in_position lista)
  (list  (max_list1 lista) 
         (list (find_in_position (max_list1 lista) lista))))
share|improve this answer
add comment

This should do the trick:

(define (find-position list element #!optional (pred eq?))
  (letrec ((loop (lambda (list count)
           (if (null? list) #f ;No such element found
               (if (pred (car list) element) count
            (loop (cdr list) (+ count 1)))))))
    (loop list 0)))


(find-position (list 1 3 13) 13)
>>> 2

share|improve this answer
add comment

Your Answer


