How do I get an item from a list at a given index in racket language?
32,366
Solution 1
Example:
> (list-ref '(a b c d e f) 2)
'c
See:
http://docs.racket-lang.org/reference/pairs.html
Solution 2
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))))))
Author by
lu1s
Updated on November 25, 2020Comments
-
lu1s over 3 years
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 thecountdown
index. Could you help me on that? -
Zelphir Kaltstahl over 7 years@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.