17

I'm trying to get an item from a list at a given index for a loop statement.

(define decision-tree-learning
  (lambda (examples attribs default)
    (cond
      [(empty? examples) default]
      [(same-classification? examples) (caar examples)] ; returns the classification
      [else (lambda () 
              (let ((best (choose-attribute attributes examples))
                    (tree (make-tree best))
                    (m (majority-value examples))
                    (i 0)
                    (countdown (length best)) ; starts at lengths and will decrease by 1
                  (let loop()
                    (let example-sub ; here, totally stuck now
                      ; more stuff
                      (set! countdown (- countdown 1))
                      ; more stuff
                      )))))])))

In this case, best is the list and I need to get its value at the countdown index. Could you help me on that?

lu1s
  • 5,600
  • 3
  • 22
  • 37
  • 2
    Instead of looping over an index and using `list-ref`, why not just loop over the list directly? – Ryan Culpepper May 10 '12 at 00:14
  • 2
    Also note that if you find yourself doing random access through the list, then it's probably not the appropriate container type for your data. Racket (as well as Scheme) provides the *vector* type that supports constant-time random access. http://docs.racket-lang.org/guide/vectors.html – dyoo May 10 '12 at 00:39
  • 1
    Thanks for the comments. I'm really new at racket lang and I appreciate all this. – lu1s May 10 '12 at 01:08

2 Answers2

35

Example:

> (list-ref '(a b c d e f) 2)
'c

See:

http://docs.racket-lang.org/reference/pairs.html

soegaard
  • 30,661
  • 4
  • 57
  • 106
8

Or build this yourself:

(define my-list-ref
    (lambda (lst place)
      (if (= place 0)
          (car lst)
          (my-list-ref (cdr lst) (- place 1)))))

but if you want to check if the list is done and don't worry by error yo can do this as well:

(define my-list-ref
    (lambda (lst place)
      (if (null? lst)
          '()
          (if (= place 0)
          (car lst)
          (my-list-ref (cdr lst) (- place 1))))))
EdChum
  • 376,765
  • 198
  • 813
  • 562
Gil Matzov
  • 213
  • 2
  • 12
  • 4
    @leo-the-manic: Easy: To understand how it works internally and to be able to use the concepts within in other contexts. You wouldn't do it in production setting, but for learning purposes it is justified. – Zelphir Kaltstahl Oct 15 '16 at 13:25