如何使用racket语言从给定索引的列表中获取项目?

时间:2012-05-09 20:08:44

标签: list scheme racket

我正在尝试从循环语句的给定索引的列表中获取项目。

(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
                      )))))])))

在这种情况下,best是列表,我需要在countdown索引处获取其值。你可以帮帮我吗?

2 个答案:

答案 0 :(得分:22)

示例:

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

请参阅:

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

答案 1 :(得分:5)

或者自己构建:

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

但如果您想检查列表是否已完成且不担心错误,您也可以这样做:

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