Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the difference between Cons and Append in scheme?

Tags:

scheme

I read both of them and they seem to both construct a single list, what's their difference?

like image 362
ProxyStudent Avatar asked Apr 08 '16 11:04

ProxyStudent


People also ask

What is append in Scheme?

The append function joins two lists together to make one. The append function is built into Scheme. It concatenates two lists, that is to say, given two lists list1 and list2 it produces a new list which starts with the same elements as list1 and finishes with those of list2 .

What does cons do in Scheme?

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.

What difference between ADD and append?

@toron Adding means putting two or more things together, such as numbers for example. Appending implies that you are attaching something to a main item. A book may have an appendix which usually gives extra information.


1 Answers

cons is the constructor for all pairs.

A proper list is () (the empty list, aka nil) or a pair where the cdr is a proper list. Any chain of pairs where the last one has () as it's cdr is a proper list (in addition to the empty list itself).

A dotted list is a pair that does not have a proper list as it's cdr. Thus a chain of pairs where the last cdr is not () matches this.

;; dotted lists
(cons 1 2)          ; ==> (1 . 2) 
(cons 1 (cons 2 3)) ; ==> (1 2 . 3) or (1 . (2 . 3))

;; proper lists
(cons 1 '())          ; ==> (1) or (1 . ())
(cons 1 (cons 2 '())) ; ==> (1 2) or (1 . (2 . ()))

append is a procedure that uses cons to make a list with all the elements of the argument lists left to right. A common implementation of append for just two lists would be:

(define (append lst tail)
  (if (null? lst)
      tail
      (cons (car lst)
            (append (cdr lst)
                    tail))))

append will fail if one of the arguments except the last is not a proper list. Tail and can be any value:

(append '(1 2 3) '(4 5))       ; ==> (1 2 3 4 5) or (1 . (2 . (3 . (4 . (5 . ())))))
(append '(1 2 3) '(4 5 . 6))   ; ==> (1 2 3 4 5 . 6) or (1 . (2 . (3 . (4 . (5 . 6)))))
(append '(1 2 3) #f)           ; ==> (1 2 3 . #f) or (1 . (2 . (3 . #f)))
(append '(1 2 . 3) '(4 5 . 6)) ; ==> error `car` of number not allowed
like image 168
Sylwester Avatar answered Sep 18 '22 12:09

Sylwester