开发者

car and cdr in Scheme are driving me crazy

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 th开发者_JAVA百科is ... give me a step or a way to solve it step by step?


Try to do it step by step:

  • cdr yields the list without the first element
  • 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


this is easy/compact way to get the value of the list.

(cadr (cadddr x))

by combining repeating functions, you get elegant easy to read statement.


(cdr x) = ((bc) d ( (ef) g ) )
(cdr(cdr x)) = (d ( (ef) g ) )
(cdr(cdr(cdr x))) = (( (ef) g ) )
(car(cdr(cdr(cdr x)))) = ( (ef) g )
(cdr(car(cdr(cdr(cdr x))))) = (g)
(car(cdr(car(cdr(cdr(cdr x)))))) = g


Have you tried using a REPL (read-eval-print-loop) such as csi? That way you can work on this interactively, which will make it easier for you to learn and work through this (and other) problems using Scheme.


do it iteratively. Also, realize that scheme always looks backwards.

(cdr x) = ( (b c) ...)
(cdr (cdr (cdr x))) = (( (ef) g))
(car (cdr (cdr (cdr x)))) = ((ef) g)
(cdr (car (cdr (cdr (cdr x))))) = (g)
(car (cdr (car (cdr (cdr (cdr x)))))) = 'g

hope that helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜