# 1. Summary of Basic Scheme¶

## 1.1 Thinking Recursively, Summary¶

1. Decide on the base cases
2. A base case is the "smallest" or "simplest" case
3. After that, assume that the function exists, and use it
4. Divide the problem up into smaller pieces
In :
(define snoc
(lambda (item lst)
(cond
((null? lst) (cons item '()))
(else (cons (car lst)
(snoc item (cdr lst)))))))

In :
(snoc 1 '()) ;; -> (1)

Out:
(1)
In :
(snoc 'a '(c b)) ;; -> (c b a)

Out:
(c b a)
In :
(snoc '4 '(1 2 3)) ;; -> (1 2 3 4)

Out:
(1 2 3 4)
In :
(define rac
(lambda (lst)
(cond
((null? lst) (error 'rac "can't take the rac of an empty list"))
((null? (cdr lst)) (car lst))
(else (rac (cdr lst))))))

In :
(rac '(1 2 3 4)) ;; -> 4

Out:
4
In :
(rac '(a)) ;; -> a

Out:
a
In :
(rac '())


Traceback (most recent call last):
File "In ", line 1, col 1, in 'rac'
File "In ", line 4, col 19, in 'error'
File "In ", line 4, col 19
RunTimeError: Error in 'rac': can't take the rac of an empty list



## 1.2 Scheme Functions¶

Scheme (like Python) can take functions as arguments, and return them. This is called "functions as first-class objects."

In :
(define add1
(lambda (number)
(+ 1 number)))

In :
(map add1 '(1 2 3))

Out:
(2 3 4)
In :
(define my-map
(lambda (f lst)
(cond
((null? lst) '())
(else (cons (f (car lst))
(my-map f (cdr lst)))))))

In :
(my-map add1 '(1 2 3))

Out:
(2 3 4)
In :
(map + '(1 2 3) '(3 4 5) '(100 100 100))

Out:
(104 106 108)

## 1.3 Higher-Order Functions¶

In :
(define compose
(lambda (f g)
(lambda (lst)
(f (g lst)))))

In :
(define my-cadr (compose car cdr)) ;; my-cadr is a <procedure>

In :
(my-cadr '(1 2 3)) ;; -> 2

Out:
2
In :
(map my-cadr '((1 2 3) (4 5 6) (7 8 9)))

Out:
(2 5 8)

## 1.4 What is a Programming Language?¶

1. a computer program
2. takes in source code in a language (often recursively defined)
3. produces either a compiled program, or interpreter

Lab03 will begin the process of implementing Scheme in Python.

In :
(import "math")

Out:
(math)
In :
(math.pow 2 3)

Out:
8.0
In :
(define expt math.pow)

In :
(expt 3 5)

Out:
243.0