Search code examples
schemeprimitive

What is the concept of "third" in Primitive function scheme?


I am new at scheme computation.

I have a given problem:

(DEFINE (third C) (CAR(CDR CDR(C))))

(third ‘(A (B C) (D E) F))

I know the concept of CDR and CAR, but I don't understand what will "third" do. I read that it is a way to define "threesome???".

I am inclined to replace the value of C by the value of the second statement next to third which is ‘(A (B C) (D E) F), is this correct?

Can you explain in simple term as possible what "third" do in this given and how can I solve this given problem?


Solution

  • In lisps the list is a fundamental data structure, and it is comprised of pairs. Traditionally, the first member of the pair is called its car, and the second member is called its cdr:

    ( car . cdr )

    Here the dot indicates that the pair is composed of two cells. Given a pair, (a . b), the accessor for the first member is also called car, and the accessor for the second member is called cdr. So:

    (car '(a . b)) --> a, and
    (cdr '(a . b)) --> b.

    To form a list, pairs are combined in the following way: the first member of the first pair is the first element of the list, and the second member of the first pair is either the empty list or a pair representing the rest of the list. So, a list of one element, e.g., (a) is represented by the pair (a . ()).

    A list of two elements, e.g., (a b) is represented by the pair (a . (b . ())). Here, the second member of the first pair is the pair (b . ()). You will note that the cdr of the list (a b) is the list (b), or equivalently (b . ()).

    A list of three elements, e.g., (a b c) is similarly represented as (a . (b . (c . ()))). A list is a pair which has either the empty list () or a pair in its cdr. There is a distinction to be made here about proper lists (the final pair must have a () in its cdr) and improper lists, but I will ignore that distinction here. And the empty list is also a list (but not a pair). To make things a bit more precise: in Scheme a list is either the empty list or a pair whose cdr is a list.

    So, car gets the first member of a list, and cdr gets the rest of the list. Given the list (a b c d) we can see that:

    (cdr '(a b c d)) --> (b c d), and
    (cdr (cdr '(a b c d))) --> (cdr '(b c d)) --> (c d), and
    (car (cdr (cdr '(a b c d)))) --> (car (cdr '(b c d))) --> (car '(c d)) --> c.

    So, given the definition:

    (define (third xs)
      (car (cdr (cdr xs))))
    

    We have:

    > (third '(a b c d))
    c
    

    I will leave it to the OP to apply this information to the question of:

    (third '(a (b c) (d e) f)) --> ?