190 likes | 313 Views
Scheme & Functional Programming. (+ 23 41) >> 64 ( - 1000 334) >> 666 (* 25 4 12) >> 1200 (+ (* 3 5) (- 10 6)) >> 19. Data Types. #t for true and #f for false Characters: #a is ‘a’, #space is ‘ ’ Strings “Hello World!” define variables: (define greeting “Hello World!”).
E N D
(+ 23 41) >> 64 (- 1000 334) >> 666 (* 25 4 12) >> 1200 (+ (* 3 5) (- 10 6)) >> 19
Data Types • #t for true and #f for false • Characters: #\a is ‘a’, #\space is ‘ ’ • Strings “Hello World!” • define variables: (define greeting “Hello World!”)
(define num 2) (* 5 num) >> 10 (define (square x) (* x x)) (square 9) >> 81 (square (+ 5 4)) >> 81 (square (square 3)) >> 81
(define (abs x) (if (< x 0) (- x) x)) • and, or, not (and (> x 5) (< x 10))
(define (factorial n) (if (= n 1) 1 (* n (factorial (- n 1)))))
Local variables: let • (let (list of bindings) (what to compute)) (let ((x 2) (y 3)) (* x y)) • Problem: can’t use x later in bindingslist • let* (let* ((x 2 ) (y (- x 2)) (*x y))
Functions as arguments Want to calculate: b Σ f(n) n=a for any functions f and next: (define (sum f a next b) (if (> a b) 0 (+ (f a) (sum f (next a) next b)))) • if (inc a) is a+1, and (cube x) is x3 what is (sum cube 1 inc 5)
lambda Functions • Remember anonymous functions in Python? That was a functional-programming feature. • (sum cube 1 inc 5) • (sum (lambda (x) (* x x x)) 1 (lambda (x) (+ 1 x)) 5)
filter • (filter <function> <list>) • (filter positive? (list 1 -1 2 -2 3 -3))
Lists (define one-through-four (list 1 2 3 4))> one-through-four> (1 2 3 4)
Head (car) and Tail (cdr) (car one-through-four)1(cdr one-through-four)(2 3 4)(car (cdr one-through-four))2
Construct a list (cons) (cons 10 one-through-four)(10 1 2 3 4)(cons 5 one-through-four)(5 1 2 3 4)
append • Can append two lists into one • This is different than cons
Empty List Keyword null is an empty list. Check for empty list: (if (null? items)
Quoting (define a 1)(define b 2)(list a b)(1 2)(list 'a 'b)(a b)(list 'a b)(a 2)
Put it in a file • I know what you’re thinking….How do I make a comment? (Semicolon for in-lines) ; Hello World (define (hello) (begin (display “Hello World!”) (newline)))
Scheme is interpreted… • but we can load a file all at once: • (load “hello.ss”)
Practice • Sum up a list • “double up” a list – for example, (doubleUp (list 1 2 3 4)) should give(1 1 2 2 3 3 4 4) • zipUp two lists - do pairings, for example, (zipUp (list 1 2 3) (list 4 5 6)) should give ((1 4) (2 5) (3 6))