Search code examples
schememaxlengthcons

Scheme cons and length


I'm studying scheme and I have just encountered my first problem:

(define x (cons (list 1 2) (list 3 4)))
(length x)
3

why the output is 3 and not 2? I have displayed x

((1 2) 3 4)

why is like that and not ((1 2) . (3 4)) ?

Thanks.


Solution

  • Maybe it's easier to see this way.

    You have:

    (cons (list 1 2) (list 3 4))
    

    If you

    (define one-two (list 1 2))
    

    you have

    (cons one-two (list 3 4))
    

    which is equivalent to

    (cons one-two (cons 3 (cons 4 '())))
    

    or

    (list one-two 3 4)
    

    which is

    ((1 2) 3 4)