NUIM/CS351 Lecture 03 Notes

CS351 Programming Paradigms
Stephen Fahey
Lecture 3

File of Code

lecture_03_code.scm

Interactions

> (list 12 13 (list 12) (quote (list 12)) 222)
(12 13 (12) (LIST 12) 222)

;;; Where you see single quote, it takes literally what follows it
;;; All predicates end in '?'.

> (equal? (quote (1 2 3)) (quote ( 1 2 4)))
#f

> (quote foo)
foo

> (equal? (quote foo) (quote bar))
#f

> (equal? (quote foo) (quote foo))
#t

> (let ((x (sin 2))) (list x x))
(0.9092.... 0.9092....)

> (let ((x(quote (sin x)))) (list x x))
(sin x  sin x)

> (let ((x(quote (sin 2)))) (list x x))
((sin 2) (sin 2)

> (car (quote (sin 2)))
sin

> (let ((x '(sin 2))) (list x (car x) (cadr x) (cdr x) (cddr x) x))
((sin 2) sin 2 (2) () (sin 2))

> 'x-x-x-x-x-
x-x-x-x-x-

;;; Using camel case is frowned upon, and in fact nearly impossible;
;;; notice the difference when the following is run: Scheme symbols are
;;; NOT CASE SENSITIVE.

> 'sin_x_using_underlines-and-hyphens-AndCamelCase
sin_x_using_underlines-and-hyphens-andcamelcase

;;; (also Barak claims that scientific studies prove that CamelCase
;;; causes cancer and osteoporosis and some kind of ugly rash.)

> '2xxxx
2xxxx

> (symbol? 'foo)
#t

> (symbol? 33)
#f

> (number? 'foo)
#f

> (symbol? '2xxx)
#t

;;; Don't use code like this:

> #o10
8

> #xf
15

> 'foo#
foo#


;;; eq? for equality

> (eq? 'foo 'bar)
#f

> (eq? 'foo 'foo)
#t

> (eq? '(ab) '(ab))
#f

~~~~~


;;;; RECURSION


~~~~~

> reverse
#<primitive:reverse>

~~~~~

;;;; REVERSE

;;; Write our own reverse

(define my_reverse
  (lambda (l)
    (if (null? l)
	'()
	(bcons (car l) (my_reverse (cdr l))))))

;;; This "conses on the back", ie "backwards cons"

(define bcons
  (lambda (x l)
    (if (null? l)
	(list x)
	(cons x (bcons x (cdr l))))))

~~~~~

> (bcons 1 (list 2 3 4))
(1 1 1 1)

> (bcons 'z '(a b c d))
(z z z z z)

;;; In the above code, z is x and (a b c d) is l

;;; Oops!  Need to fix bug:

(define bcons
  (lambda (x l)
    (if (null? l)
	(list x)
	(cons (car l) (bcons x (cdr l))))))

~~~~~

> (bcons 'z '(a b c d))
(a b c d z)

> (my_reverse '(a b c d e f g))
(g f e d c b a)

~~~~~

;;;; HOW CONS WORKS (representation inside the computer)

pointer to a cons cell   
-> [ 1st_element | pointer_to_rest_of_list ]

(a b c)

is represented as: pointer-to-A

A:[a | pointer-to-B]
B:[b | pointer-to-C]
C:[c | / ]