Question

I'm not sure how to do this and couldn't find an example of it anywhere. How do I find the position of a value in a list. For example I have a (define findValue x lst) which accepts a value and list and from that list I want type in (findValue 3 '(1 2 0 8 5 6)) and it should return 0 since the value in position 3 is 0. From my understanding and how it usually is position 3 would be 8 and not 0 in arrays at least. How does it work in here and how do I approach this problem?

Thanks!

Was it helpful?

Solution

Try:

(define (at n xs)
    (cond ((null? xs) xs)
          ((= n 1) (car xs))
          (else (at (- n 1) (cdr xs)))))

Use it as follows:

(at 3 '(1 2 0 8 5 6)) => 0

For zero-based indexing change the (= n 1) check on the 3rd line to (= n 0).

Edit: So you want to partially apply the at function? All you need is curry and flip. They are defined as follows:

(define (curry func . args)
    (lambda x (apply func (append args x))))

(define (flip func)
    (lambda (a b) (func b a)))

Using curry and flip you can now partially apply at as follows:

(define position (curry (flip at) '(1 2 0 8 5 6)))

You can now use position as follows:

(position 3) => 0
(position 4) => 8

Hope that helped.

OTHER TIPS

Usually indexes are counted starting from 0, and your understanding is correct. But if you're required to implement a findValue procedure that starts counting indexes from 1, it's not that hard to write the procedure:

(define (findValue idx lst)
  (cond ((or (null? lst) (negative? idx)) #f)
        ((= idx 1) (car lst))
        (else (findValue (sub1 idx) (cdr lst)))))

Explanation:

  • If the list received as parameter is empty or the index becomes negative, we treat that as a special case and return #f to indicate that the value was not found
  • If the index is 1 then we're right where we wanted, so it's time to return the current element
  • Otherwise advance the recursion: subtract one from the index and advance one position over the list

It works as expected:

(findValue  3 '(1 2 0 8 5 6))
=> 0
(findValue -1 '(1 2 0 8 5 6))
=> #f
(findValue  7 '(1 2 0 8 5 6))
=> #f
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top