Scheme

Feel the Cool

Andy Balaam

Contents

Simple

Simple - The one thing you can do






(operator operand1 operand2 ...)

Simple - Arithmetic

> (+ 3 4)
7
> (* 3 4)
12
> (+ 5 (* 2 2))
9

Simple - Defining values

> (define foo 3)

> foo
3
> (* foo 4)
12

Simple - Defining functions

> (define (square x) (* x x))

> (square 4)
16
> (+ (square 2) (square 3))
13

Simple - Flow control


(define (abs x)
        (if (< x 0)
            (- x)
            x))


> (abs -3)
3
> (abs 3)
3

Simple - The one data structure




(value1 value2 value3 ...)


; To make one, we write:
(list value1 value2 value3 ...)

Simple - Using data

> (sort (list 4 6 5))
(4 5 6)
> (length (list 1 2))
2

Weird

Weird - Functional - list manipulation

> (define my-list (list 1 2 3 4 5))

> my-list
(1 2 3 4 5)
> (car my-list)
1
> (cdr my-list)
(2 3 4 5)

Weird - Functional - recursion


(define (sum list-of-values)
        (if (= 1 (length list-of-values))
            (car list-of-values)
            (+ (car list-of-values)
               (sum (cdr list-of-values)))))


> (sum (list 5 6 7))
18

Weird - Dynamic typing

> (define (improved-code q) (* q 2))

> (define code-quality 4)

> (improved-code code-quality)
8
> (define code-quality "poor")

> (improved-code code-quality)
*: expects type  as 1st argument, given: "poor"; other arguments were: 2

Weird - Functions are values

> (define (double value) (* 2 value))

> (define (apply-twice fn value) (fn (fn value)))

> (apply-twice double 2)
8

Weird - Data or code? (1)


; Prerequisites:
(define (swap-2-3 x)
        (list (car x)
              (caddr x)
              (cadr x)))

> (swap-2-3 (list 1 2 3))
(1 3 2)

> (swap-2-3 (list "a" "b" "c"))
("a" "c" "b")

Weird - Data or code? (2)

> (define four-over-two (list '/ 4 2))

> four-over-two
(/ 4 2)
> (eval four-over-two)
2
> (define switched (swap-2-3 four-over-two))

> (eval switched)
1/2
> switched
(/ 2 4)

Cool

Cool - Everything is generic

> (sort (list 5 4 3 2 1) <)
(1 2 3 4 5)
> (sort (list "abc" "a" "ab") string<?)
("a" "ab" "abc")

Cool - Generating code is easy (1)


(define (d-zero name)
        (list 'define (string->symbol name) 0))

> (d-zero "a")
(define a 0)

(define (d-zero-list names) (map d-zero names))

(define mycode (d-zero-list (list "a" "b" "c")))
> mycode
((define a 0) (define b 0) (define c 0))

Cool - Generating code is easy (2)

> mycode
((define a 0) (define b 0) (define c 0))
> (for-each eval mycode)

> a
0
> b
0
> c
0
> d
reference to undefined identifier: d

Cool - Metaprogramming

(define (double x) (* x 2))
(define (square x) (* x x))

(define (apply-twice fn x)
        (fn (fn x)))

(define (quadruple x) (apply-twice double x))
(define (pow-4 x)     (apply-twice square x))

> (quadruple 3)
12
> (pow-4 3)
81

Still to come - The really good bits

Discussion





$ sudo apt-get install plt-scheme
$ mzscheme
Welcome to MzScheme v4.2.1 [3m], Copyright (c) 2004-2009 PLT Scheme Inc.
>