Scheme question/help

JC0133

Senior member
Nov 2, 2010
201
1
76
;to compute the number of elements in a list.

(define (myListLength Lst)
(if (null? Lst)
0
(+ 1 (myListLength (cdr Lst) ))
)
)



;to compute the sum of elements in a list of numbers

(define (myListSum Lst)
(if (null? Lst)
0
(+ (car Lst) (myListSum (cdr Lst) ))
)
)

I am taking a Scheme class and I was doing well up until this point. My professor handed out some examples and i am having serious trouble understanding them.

I don't get how these functions work?? I don't understand how it is going threw the entire list like a loop but its a IF statement?

I also don't understand how +1 can be added to list since its not a number.

Any insight on this would be greatly appreciated.
 

Pia

Golden Member
Feb 28, 2008
1,563
0
0
Just indent it sensibly and read it out loud in English, and you'll easily see it's correct. The list length, for example:
Code:
(define (myListLength Lst)
    (if (null? Lst)
        0
        (+ 1 (myListLength (cdr Lst)))))
If the list is empty, its length is 0.
Otherwise, the length is 1 plus the length of rest of the list (everything except the frontmost item).

1 isn't being added to a list, but to another number which is the value of myListLength for the rest of the list.
 

JC0133

Senior member
Nov 2, 2010
201
1
76
thank you, this all makes sense now.

I do have another question. trying to understand how to use cons.

> (cons (cons 1 2) (cons 3 4) )
((1 . 2) 3 . 4)

Why does this not create ( (1.2) . (3.4) )

How can I create that using cons? Am I using cons wrong here?
 

Pia

Golden Member
Feb 28, 2008
1,563
0
0
You are doing the right thing and getting ((1 . 2) . (3 . 4)). Confirmation here:
http://en.wikipedia.org/wiki/Cons

The debug output is just displayed differently than you expect. Probably the most common use of cons is to form lists:
Code:
# this is a list
(cons 1 (cons 2 (cons 3 '() )))
# shows up as (1 2 3) while debugging

So that lists get printed without dots, the printing of a dot is omitted for a cons where the cdr is another cons.