Kursens personal Kursens syfte Kursens innehåll TDDC74 Programming:

advertisement
Kursens personal
TDDC74 Programming:
Abstraction and Modelling
SICP 1 – Lecture 1-3
Annika Silvervarg
Kursens syfte
Annika Silvervarg
Anders Haraldsson
Jonas Wallgren
Peter Dalenius
Jalal Maleki
Lise-Lott Andersson
Kursens innehåll
Kursens syfte är att studenterna ska utveckla
förmåga att representera och lösa problem med
hjälp av konstruktioner i datorspråk. Efter avslutad
kurs ska studenterna kunna:
SICP1
redogöra för grundläggande datavetenskapliga begrepp
relaterade till programmering och programspråk, särskilt
funktionella språk
metodiskt lösa programmeringsrelaterade problem i en
interaktiv programutvecklingsmiljö
representera problem och lösningar till dessa i form av
rekursiva och iterativa algoritmer och kunna uppskatta tid- och
rymdkomplexiteten för enklare fall
konstruera abstraktioner som möjliggör design av program som
är lättförståliga, återanvändbara och kan underhållas lättare
genomföra ett mindre programmeringsprojekt
SICP3
Kursens organisation
Föreläsningar
Lektioner
Laborationer
Projekt
Duggor
–
Abstraktioner baserat på procedurer
SICP2
–
–
Abstraktioner baserat på data
Abstraktioner baserat på objekt
Kursens examination
Duggor, betyg 3,4,5
Projekt, betyg G, VG
Laborationer, betyg G (inlämnade i tid)
3+G=3
4+G=4
5+G=6
3 + VG = 4*
4 + VG = 5*
5 + VG = 5+*
* Förutsatt att laboration lämnats in i tid
1
Kursbok
Programming
Computational processes
… manipulate data
… are controlled by rules, i.e. a program/procedure
… written in a specific programming language
… in this course Scheme
Elements Of Programming
Primitive expressions
Means of combination
Means of abstraction
Expressions
Primitive
–
Compound
–
–
–
Primitive Expressions
Constants
Names
eg. numbers: 1, 3.14
eg. application of mathematical primitive procedure on
numbers: (+ 1 3.14)
(operator operand … operand)
Can be nested: (+ (* 2 3) (- 4 5))
Constants
truth-value: #t, #f
integer: 42, +1789, -2
rational: 3/4, -22/7
floating: 3.1415, -10e10, 2e-3
complex: 3.1+4i, 2-3i
2
Names
A name is a sequence of characters that does not
constitute a number in Scheme:
+
square
week23
i-am-a-name-in-scheme-too
+inf.0
http://www.google.com/
-1+
2+2
Evaluating Numbers
Read the number
Evaluate it
Print the value
Read-Eval-Print
Read an expression
Evaluate it according to given rules
Print the result
Evaluating Truth Values
#t and #f are the truth values in Scheme
#t represents the value ’true’
#f represents the value ’false’
4 is read and we get ’4’ and it is evaluated to the
number 4
Compound Expressions
Procedure Application
Special Forms
Abstraction Operators
Compound Expressions
Primitive Function Application
(<function> <arg1> <arg2> ...)
User-Defined Function Application
(<function> <arg1> <arg2> ...)
Special Forms:
(if <condition> <then> <else>)
(and <exp1> <exp2> ...)
(or <exp1> <exp2> ...)
Abstraction:
(define <name> <value>)
(lambda <args> <body>)
grouping together many procedures
3
Functions In Mathematics
What element in R (Range) corresponds to an
element in D (Domain)
R and D are both sets
The function mapping D to R is also a set – a set of
pairs chosen from D and R
Functions In Programs
How to map elements of D to R?
Use algorithms or descriptions that do the mapping
Example Function
Domain: {..., -2, -1, 0, 1, 2, ...}
Range: {..., -2, -1, 0, 1, 2, ...}
Function: {..., < -2, 4 >, < -1, 1 >, < 0, 0 >, < 1, 1 >,...}
(LAMBDA (N) (* N N))
Parameter: N
Body: (* N N)
Example:
(LAMBDA (N) (* N N)) that given N computes N*N
Example:
(LAMBDA (R) (* 2 (* 3.1415 R)))
((LAMBDA (N) (* N N)) 7)
Parameter: N
Body: (* N N)
Argument: 7
Value: 49
Parentheses
Parentheses are for helping us to understand the
structure of our programs, not for confusing us
((LAMBDA (N) (* N N)) 7)
At the same time we must admit they are a pain ...
but we have no choice
4
Special forms
Tests
–
–
if
cond
Logical operators
–
–
–
and
or
not
COND
(cond (predicate-1 consequence-1)
(predicate-2 consequence-2)
...
(predicate-n consequence-n))
(lambda (amount)
(cond ((< amount 0) 0)
((< amount 10000) 0.5)
((< amount 50000) 1.1)
((>= amount 50000) 1.5)))
Combining Logical Operators
(or (and (> x 2) (< x 6))
(and (> x -6) (< x -2)))
IF
(if <condition> <then> <else>)
(lambda (amount)
(if (< amount 10000) 0 1.5))
Logical Operators Examples
(and <e1>,…, <en>)
(or <e1>,…, <en>)
(not <e1>)
(and (> x 2) (< x 6))
(or (> x 2) (< x -2))
(not (< x 3))
What Is Abstraction?
Ignoring details
Packaging details
Concentrating on the whole rather its parts
(not (odd? x))
5
Abstraction In Programming
Giving a name to 3.1415 is abstraction
Giving a name to (LAMBDA (N) (* N N)) is
abstraction
Abstraction In Scheme
(define pi 3.1415)
(define square (lambda (n) (* n n)))
(define circle-area
(lambda (r) (* pi (square r))))
Why Abstraction?
Which is better?
(define circle-area
(lambda (r) (* pi (square r))))
Abstraction Operators
define
lambda
Block-structures: grouping procedures
(define circle-area
(lambda (r)
(* pi ((lambda (n) (* n n)) r))))
define
Is used to give names to values and procedures
For the time being, let’s just imagine that define puts
names and their values in some sort of table.
In chapter 3 of the book more detail is revealed
lambda-expression
(lambda <args> <body>)
Creates a function object with the given arguments
and body
6
Shorthand/Syntactic sugar
Naming and defining procedures can be done in one
step
(define area
(lambda (r) (* pi (square r))))
(define (area r) (* pi (square r)))
Evaluating the Special Forms: if
(if <condition> <then> <else>)
Evaluate <condition>, if true then evaluate <then>
otherwise evaluate <else>
Evaluating Function Application
Substitution model:
Given a procedure call of the form:
(<function> <arg1> <arg2> ...)
–
–
Evaluate the arguments
Replace occurrences of the parameters with value of the
corresponding arguments in the body of <function> and
evaluate the resulting expression
This is according to the applicative method
Evaluating the Special Forms: cond
(cond (predicate-1 consequence-1)
(predicate-2 consequence-2)
...
(predicate-n consequence-n))
Evaluate predicate-i, if true, evaluate consequence-i
and return its value as the value of the whole CONDexpression
Evaluating the Special Forms: and
Evaluating the Special Forms: or
(and <arg-1> <arg-2> ...)
(or <arg-1> <arg-2> ...)
Evaluate arguments from left to right until a #f value
reached in which case return #f, return #t otherwise
Evaluate arguments from left to right until a #t value
reached in which case return #t, return #f otherwise
7
Cond, cond -> if
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x)))
(if (> x 0)
x
(if (= x 0)
0
( - x)))
If, if -> cond
(if (>= x 0) x (- x))
(cond ((>= x 0) x)
(else (- x)))
(if (> x 0)
x
(if (= x 0)
0
(if (< x 0)
(- x))))
Distance function
Define a function that takes two coordinates (i.e. 4
numbers) as argument and calculate the distance
between them.
Distance function
(define distance
(lambda (x1 y1 x2 y2)
(sqrt (+ (square (- x2 x1)) (square (- y2 y1))))))
(define square
(lambda (n) (* n n)))
Substitution model
(distance 0 0 3 4)
(sqrt (+ (square (- 3 0)) (square (- 4 0))))
(sqrt (+ (square 3) (square 4)))))
(sqrt (+ (* 3 3) (* 4 4)))
(sqrt (+ 9 16))
(sqrt 25)
5
Procedures and Processes
When a procedure is evaluated or executed, it
creates a process
8
Procedures and Processes
Recursive Processes
Iterative Processes
Recursion
Defining the meaning of a function in terms of itself
Nothing strange about this
n! = n * (n-1)!
0! = 1, N! = N * (N-1)!
Substituion Model
(define fact
(lambda (n)
(if (= n 0)
1
(* n (fact (- n 1))))))
Use substitution model to find (fact 4):
(fact 4)
(* 4 (fact 3))
(* 4 (* 3 (fact 2)))
(* 4 (* 3 (* 2 (fact 1))))
(* 4 (* 3 (* 2 (* 1 (fact 0))))) at this stage expansion is complete
(* 4 (* 3 (* 2 (* 1 1))))
(* 4 (* 3 (* 2 1)))
(* 4 (* 3 2))
(* 4 6)
24
trace.ss
Linear Recursive Process Characteristics
(require (lib "trace.ss"))
(trace fact)
A recursive call to the procedure
Each recursive creates a delayed computation
Time complexity grows linearly with respect to the
size of the input parameter O(n)
Space complexity grows linearly with respect to the
size of the input parameter O(n)
9
Iterative Factorial
(define (fact n)
(fact-iter n 1)
(define (fact-iter n prod)
(if (= n 0)
prod
(fact-iter (- n 1)
(* n prod))))
Iterative Process Characteristics
A recursive call
The recursive call does not create delayed
computation
Time complexity is linear with respect to the size
input parameter O(n)
Space complexity is constant (independent of the
size of input) O(k)
Recursive Fibonacci
(define fib
(lambda (n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (fib (- n 1))
(fib (- n 2)))))))
Substitution model
(fact 4)
(fact-iter 4 1)
(fact-iter (- 4 1) (* 4 1))
(fact-iter 3 4)
(fact-iter (- 3 1) (* 3 4))
(fact-iter 2 12)
(fact-iter (- 2 1) (* 2 12))
(fact-iter 1 24)
(fact-iter (- 1 1) (* 1 24))
(fact-iter 0 24)
24
Fibonacci Numbers
0, 1, 1, 2, 3, 5, 8, 13, ...
Tree Recursive Process
(fib 5)
(+ (fib 4) (fib 3))
(+ (+ (fib 3) (fib 2)) (fib 3))
(+ (+ (+ (fib 2) (fib 1))(fib 2)) (fib 3))
(+ (+ (+ (+ (fib 1) (fib 0))(fib 1))...)...)
10
Tree Recursive Processes
Multiple recursive calls in the same expression
Recursive call creates delayed computation
Time complexity grows exponentially O(kn)
Space complecity is linear O(n)
Newtons metod för approximering av kavdratrötter
Gör en intital gissning (valigtvis 1)
Dela det sökta talet med gissningen
Ta medelvärdet av gissningen och kvoten för att få
en ny gissning
Upprepa de två sista stegen
Newtons metod för approximering av kavdratrötter
Iterative Fibonacci
(define fiter
(lambda (n f0 f1 count)
(if (= count n)
f1
(fiter n
f1
(+ f0 f1)
(+ count 1)))))
Newtons metod för approximering av kavdratrötter
(define sqrt
(lambda (n)
(sqrt-help 1 n)))
(define sqrt-help
(lambda (guess n)
(if (good-enough? guess n)
guess
(sqrt-help (improve guess n) n))))
Newtons metod för approximering av kavdratrötter
(define good-enough?
(lambda (guess n)
(< (abs (- (square guess) n)) 0.001)))
(define improve
(lambda (guess n)
(average guess (/ n guess))))
(define abs
(lambda (n)
(if (< n 0) (- n) n)))
(define average
(lambda (x y)
(/ (+ x y ) 2)))
11
Procedures Without Arguments
(define random-number
(lambda ()
(random 10)))
(random-number)
>6
Scope
(define add10
(lambda (number)
(+ number 10)))
The scope of ’number’ is the body of this procedure
and it can only be used there
(add10 3)
> 13
number
>ERROR
Scope: Local or Global
Shadowing
(define number 23)
(define number 23)
(define add10
(lambda (number)
(+ number 10)))
(define add10
(lambda (number)
(+ number 10)))
(add10 10)
> 20
(add10 number)
> 33
Add10 shadows the global value of number inside its
body
Higher-Order Procedures
Procedures as arguments
Procedures as returned values
Various Sums
(define (sum-ints a b)
(if (> a b)
0
(+ a
(sum-ints (+ a 1) b))))
(define (sum-squares a b)
(if (> a b)
12
Similarities
(define (sum-ints a b)
(if (> a b)
0
(+ a
(sum-ints (+ a 1) b))))
General Sum
(define (sum a b term)
(if (> a b)
0
(+ (term a)
(sum (+ a 1) b term))))
(define (sum-squares a b)
(if (> a b)
General Sum
(define (sum-squares a b)
(sum a b square))
(define (sum-cubes a b)
(sum a b cube))
How to write sum-ints?
Similarities
(define (sum a b term next)
(if (> a b)
0
(+ (term a)
(sum (next a) b term next))))
Two Kinds of Accumulation
(define (sum a b term next)
(if (> a b)
0
(+ (term a)
(sum (next a) b term next))))
(define (mult a b term next)
(if (> a b)
1
(* (term a)
(mult (next a) b term next))))
Accumulation in General
(define (acc a b term next init op)
(if (> a b)
init
(op (term a)
(acc (next a) b term next init op))))
(define (mult a b term next)
(if (> a b)
1
(* (term a)
(mult (next a) b term next))))
13
Accumulation in General
(define (acc a b term next init op)
(if (> a b)
init
(op (term a)
(acc (next a) b term next init op))))
Procedures as returned values
The composition of two functions f and g is defined
as f(g(x))
Define a procedure compose that implements
composition
(define (sum a b term next)
(acc a b term next 0 +))))
compose
make-greeter
(define (compose f g)
(lambda (x) (f (g x))))
(define (make-greeter name)
(lambda () (display “Hello ”) (display name)))
(define test-newton (compose square sqrt))
(define test-newton
(lambda (x) (square (sqrt x))))
(define greet (make-greeter “Annika”))
(define greet
(lambda () (display “Hello ”) (display “Annika”)))
(test-newton 1)
> 1.0
(test-newton 2)
> 2.0000060073048824
(greet)
Hello Annika
>
LET, LET*
LET and LET* are a kind of alternative syntactic
forms for constructing local variables in procedures
(let ((<var1> <exp1>)
(<var2> <exp2>)
…
(<varn> <expn>))
body)
Facilitate understandning of programs
Can be used to avoid repeated computations
Let binds it variables in parallell, use let* for
sequential
LET example
(define fiter
(lambda (n f0 f1 count)
(let ((new-f0 f1)
(new-f1 (+ f0 f1)))
(if (= count n)
f1
(fiter n
new-f0
new-f1
(+ count 1))))))
14
LET example
(define (sum-and-test x y test-fn)
(let ((sum (+ x y)))
(if (test-fn sum)
sum
(display “The sum did not pass the test”))))
LET example
(define (sum-and-test x y test-fn)
(define (helper sum test-fn)
(if (test-fn sum)
sum
(display “The sum did not pass the test”)))
(helper (+ x y)))
(define (sum-and-test x y test-fn)
((lambda (sum test-fn)
(if (test-fn sum)
sum
(display “The sum did not pass the test”)))
(+ x y)))
Where Do Algorithms Come From
Thinking and Problem Solving
Fortunately many problems are solved already.
”Just” translate the solutions to algorithms
Many mathematical formulas can easily be
translated to algorithmic descriptions
Example
Equation: C/100=(F - 32)/180
can be formulated as two algorithms that compute C
or F
(define c (lambda (f)
(* 100 (/ (- f 32) 180))))
(define f (lambda (c)
(+ (/ (* c 180) 100) 32)))
Errors
Syntactic Error
Expression impossible to evaluate
Semantic Error
Meaningless expressions
Algorithmic Error
Solving the wrong problem
Summary
Expressions
–
Primitive
Constants
Names
–
Compound
Function applications
Special forms
If
Cond
– Logical operators: and, or, not
–
–
Abstraction
–
–
Lambda
Define
15
Summary
Evaluation and substitution model
Procedures and processes
–
Recursive procedures
Recursive processes
Iterative processes
Tree-recursive processes
Scope: local and global variables
–
Let
Higher order functions
–
–
Functions as arguments
Functions as returned values
16
Download