Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an item from a list at a given index in racket language?

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?

like image 970
lu1s Avatar asked May 09 '12 20:05

lu1s


People also ask

What is a pair in racket?

Pairs and Lists in The Racket Guide introduces pairs and lists. A pair combines exactly two values. The first value is accessed with the car procedure, and the second value is accessed with the cdr procedure. Pairs are not mutable (but see Mutable Pairs and Lists).

What is a list in racket?

The list is the fundamental data structure of Racket. A list is a sequence of values. A list can contain any kind of value, including other lists. A list can contain any number of values. If a list has zero values, it's called the empty list.

How do you find the last element of a list in racquet?

First find the lenght of a list by cdring it down. Then use list-ref x which gives the x element of the list. For example list-ref yourlistsname 0 gives the first element (basically car of the list.) And (list-ref yourlistsname (- length 1)) gives the last element of the list.


2 Answers

Example:

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

See:

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

like image 101
soegaard Avatar answered Oct 16 '22 10:10

soegaard


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))))))
like image 43
Gil Matzov Avatar answered Oct 16 '22 10:10

Gil Matzov