Presentation is loading. Please wait.

Presentation is loading. Please wait.

Scheme : Definitions and Expressions. Scheme : Functions (define (seven x) (* x 7))

Similar presentations


Presentation on theme: "Scheme : Definitions and Expressions. Scheme : Functions (define (seven x) (* x 7))"— Presentation transcript:

1 Scheme : Definitions and Expressions

2

3 Scheme : Functions (define (seven x) (* x 7))

4

5 Scheme : Functions (define (sum x y) (+ x y))

6

7 Scheme : Conditionals (1) (define (test x) (cond ( (> x 0)1) ( (= x 0)0) ( (< x 0)-1)))

8

9 Scheme : Conditionals (2) (define (test2 x) (if (< x 0)(- x) x))

10

11 Scheme : Recursion (define (sum n) (if (= n 1)1 (+ n (sum(- n 1))))) sum the numbers 1 to N (e,g, 1 to 4) 4 + 3 + 2 + 1 = 4 + (3 + 2 + 1) = 4 + 3 + (2+1) = 4 + 3 + (2) + 1 (sum 4) = 4 + (sum 3) =

12

13 Scheme : Recursion : The Factorial Function (1) How many ways can you get n people to sit in n chairs ? n = 3. (A,B,C)n = 4. (A,B,C,D)

14

15 I lost the number of my new mobile phone How can I find the number ? Get my girlfriend to phone every single mobile number. (OK I’ll cook supper!) Approximate solution: Say a mobile number has 10 digits (actually 11) and each digit can be 0 – 9 (10 possibilitities). So the solution is 10! How long will this take? Calculatore!

16

17 Scheme : Recursion : The Factorial Function (2) (define (fact n) (if (= n 1)1 (* n (fact (- n 1)))))

18

19 I lost the number of my new mobile phone How can I find the number ? Get my girlfriend to phone every single mobile number. (OK I’ll cook supper!) Approximate solution: Say a mobile number has 10 digits (actually 11) and each digit can be 0 – 9 (10 possibilitities). So the solution is 10! How long will this take? Calculatore! (fact 10)

20

21 Functional Recursion // Imperative Iteration (define (fact n) (if (= n 1)1 (* n (fact (- n 1)))))

22

23 Fundamental Principles of Recursion A recursive function must call a simplified version of itself. This is guaranteed to “bottom out” (to halt). Any call to itself would produce an infinite regress. Don’t run this … ah go on then.. (define (factsr n) (if (= n 1)1 (* n (factsr n))))... and wait for the error message... or worse

24


Download ppt "Scheme : Definitions and Expressions. Scheme : Functions (define (seven x) (* x 7))"

Similar presentations


Ads by Google