简体   繁体   中英

Racket lang: access element in list

Give a single function to access the element a in the list L.

(define L '(1 2 (a 3 4 5)))

Following the form (define id expr) which binds id to the result of expression I have tried the following:

(define L '(1 2 (a 3 4 5) (car(cdr L))))

cdr accesses the tail of the list, ie a 3 4 5, if I am not mistaken, and then I apply car on the tail to access the head of the list, ie a. However, it is not working on DrRacket IDE.

I think you meant to do this:

(define L '(1 2 (a 3 4 5)))

(car (car (cdr (cdr L))))
=> 'a

Which can also be written as:

(caaddr L)
=> 'a

You included the (car(cdr L)) part inside the list L .

> (define L '(1 2 (a 3 4 5) (car(cdr L))))
> L
(list 1 2 (list 'a 3 4 5) (list 'car (list 'cdr 'L))) ;; oh no

But that still doesn't extract the 'a because you need to access car of the inner list:

(define L '(1 2 (a 3 4 5)))
(car (car (cdr (cdr L))))
;; or (caaddr L)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM