I'm facing a problem with the car
and cdr
functions
for example:
first I defined a list called it x
(define x (a (bc) d ( (ef) g ) ))
so x now is equal to (a (bc) d ( (ef) g ) )
now for example I need to get the g from this list using only car
and cdr
(!! noshortcuts as caddr cddr !!) the correct answer is:
(car(cdr(car(cdr(cdr(cdr x))))))
But how? I work according to the rules (the car
gives the head of the list and cdr
gives the tail)
and instead of getting the answer above, I keep reaching wrong answers. Can anyone help me in understanding this ... give me a step or a way to solve it step by step?
In Scheme, car , cdr , and cons are the most important functions. The cons function is used to construct pairs and pairs are used to construct the lists. The car and cdr are used to access data and return accordingly first and second element from a pair.
CDR is the Acronym for “Crash Data Retrieval” This EDR data is also referred to as "crash data". CDR technicians and experts connect their EDR tool to an automobile allowing them to communicate with the vehicle and retrieve the EDR data file.
The origins of the names for car and cdr , on the other hand, are esoteric: car is an acronym from the phrase “Contents of the Address part of the Register”; and cdr (pronounced “could-er”) is an acronym from the phrase “Contents of the Decrement part of the Register”.
The other constructor, cons , is used when you already have a list and you want to add one new element. Cons takes two arguments, an element and a list (in that order), and returns a new list whose car is the first argument and whose cdr is the second.
Try to do it step by step:
car yields the first element of a list
x is (a (bc) d ( (ef) g ))
(cdr x) is ( (bc) d ( (ef) g ))
(cdr (cdr x)) is ( d ( (ef) g ))
(cdr (cdr (cdr x))) is ( ( (ef) g ))
(car (cdr (cdr (cdr x)))) is ( (ef) g )
(cdr (car (cdr (cdr (cdr x))))) is ( g )
(car (cdr (car (cdr (cdr (cdr x)))))) is g
do the transforms one at a time. cdr gives you a list without the first element, car gives you the first element.
(cdr (a (bc) d ( (ef) g ) )) -> ( (bc) d ( (ef) g ) )
(cdr ( (bc) d ( (ef) g ) )) -> ( d ( (ef) g ) )
(cdr ( d ( (ef) g ) )) -> ( ( (ef) g ) )
(car ( ( (ef) g ) )) -> ( (ef) g ) <- pulls the first element out, which happens to be a list itself
(cdr ( (ef) g )) -> (g)
(car (g)) -> 'g
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With