Intro to Scheme – The Greatest Language That Ever Was – Lists



Intro to Scheme – The Greatest Language That Ever Was – Lists

0 0


scheme-presentation


On Github keeyon2 / scheme-presentation

Intro to Scheme

The Greatest Language That Ever Was

Created by Keeyon Ebrahimi

What is Scheme

  • Functional Programming Language
  • One of the two dialects of Lisp
  • Created to teach Functional Programming

Scheme Basics

Every expression is either an atom or a list You evaluate a list by applying the first element of the list to the rest of the arguments. Iteration (looping) in Scheme is accomplished via recursion Parentheses contain expressions

Lists

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

> '(1 2 3 4)
(1 2 3 4)

> (quote (1 2 3 4))
(1 2 3 4)

Lists can be nested

> '(1 2 (3 4) 5 6)
(1 2 (3 4) 5 6)

Defining Variables

> (define x 5)
> x
5

Defining Function

> (define (f x y)
    (+ x y))

> (f 5 3)
8

Conditionals

> (define x 5)
5

> (if (= x 3) 'yes 'no)
no

> (cond ((= x 3) "x is three")
        ((= x (- 6 1)) 5)
        (else 'I_DUNNO))
5

List Operations

Car Cdr Cons

Car

Accesses the first element of a list

(car '(3 4 5 6))
3

Cdr

Returns the rest of the the list after Car

(cdr '(1 2 3 4))
(2 3 4)

Example using Car and Cdr

Here is a function that that accesses the nth element of a list

> (define (nth n L)
    (cond ((= n 1) (car L))
        (else (nth (- n 1) (cdr L)))))

> (nth 4 '(2 4 6 8 10 12))
8

Cons

(cons x L) creates a new list whose first element is x and whose subsequent elements are the elements of the list L

> (cons 3 '(4 5 6))
(3 4 5 6)

Append

Combines 2 lists into a single list

(append '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)

Now Lets write our own version

(define (app L1 L2)
  (cond ((null? L1) L2)
        (else (cons (car L1)  (app (cdr L1) L2)))
        ))
> (app '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)

Map

MAP applies a function to every element of a list, returning a list of the results

> (define (f x) (+ x 3))

> (map f '(2 4 6 8 10))
(5 7 9 11 13)

Lambda

(lambda (inputs) (operations))

> map (lambda (x) (* x 3)) '(1 2 3 4))
(3 6 9 12)

Let

Let Introduces local Variables

(define (foo)
  (let ((x 3)
        (y (+ 7 4)))
    (* x y)))
> (foo)
33

Also have LET* and LETREC

Thank you Major League Hacking!!