1 / 49

Adopted from slides by: Andrew Davison , Computer Eng . Software Lab I I , PSU , 2014.

Functional Programming with Scheme. Adopted from slides by: Andrew Davison , Computer Eng . Software Lab I I , PSU , 2014. Overview. Constants (names) Functions Lists No-name Functions: lambda cond Recursion Higher Order Functions More on Scheme Using DrScheme.

ora-hudson
Download Presentation

Adopted from slides by: Andrew Davison , Computer Eng . Software Lab I I , PSU , 2014.

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functional Programming with Scheme Adopted from slides by:Andrew Davison,Computer Eng.Software Lab II, PSU, 2014.

  2. Overview • Constants (names) • Functions • Lists • No-name Functions: lambda • cond • Recursion • Higher Order Functions • More on Scheme • Using DrScheme

  3. 1. Constants (names) myPi is defined here myPi is evaluated then printed 'myPi is not evaluated 'pi is pre-defined

  4. 2. Functions • A function call is written as: (operator arg1 arg2 … argn) • For example: (+ 23) means 2 + 3

  5. Function Call Examples The + operator (and other arithmetic) operators can take any number of arguments. The same as: (2+3)*(1+2)

  6. Test Functions (Predicates) • Test functions return boolean values true or false. • Their names end with a '?' • e.g. number?char?

  7. Defining Functions (v.1) Similar C code is:int sq(int x) { return x*x; }

  8. Similar C code is:int myMax(int x,int y) { if (x > y) return x; else return y; }

  9. Combining Functions • Scheme functions can be easily combined together • make a function call be the argument of another function function call arguments

  10. 3. Lists • List values are placed inside (list …): • (list ) // an empty list • (list 1 2 3) // a list of numbers • (list 'a 'b 'c) // a list of names • (list (list 1 2) (list 2 3 4)) // a list of two lists • If the language includes list abbreviations, then (list ...) can be written as '(...) • '(1 2 3) is the same as (list 1 2 3)

  11. Basic List Operations • (null? x) • returns true is x is an empty list; otherwise returns false • (car x) • returns the first element (head) of a non-empty list x • (cdr x) • returns the tail of a non-empty list x • everything except the first element continued

  12. (cadr x) • returns the head element of the tail of x • (cons h l) • makes a new list where the head is h, the tail is l • (list arg1 arg2 … argn) • places all of its arguments into a new list

  13. List Operation Examples

  14. plusList plusList pulls out the first two arguments of a list and adds them

  15. Some Other Useful List Functions • (length x) • returns the length of a list x • (append x y) • makes a new list by appending list x onto the front of list y • (reverse x) • makes a list by reversing the list x and many, many more... continued

  16. combining reverse and append

  17. 4. No-name Functions: lambda Similar to a C-like function call: ??(3) Similar to the C-like code: int ??(int x) { return x *x; } The language 'level' must be increased for lambda to be supported.

  18. Defining Functions (v.2) Similar to the C-like code: sq2 = int ??(int x) { return x * x; }

  19. Why have lambda? • For simple examples (like ours), there is no need for lambda. • lambda becomes very useful in higher order programming, where data and functions need to be translated into each other • e.g. parsing, AI

  20. 5. cond: the multi-branch if Similar to the C code: int sizer(int x) { if (x == 0) return 0; else if (x > 0) return 1; else return -1; }

  21. 6. Recursion • Base case: • the function returns an answer and stops • Recursion step: • the body of the function calls itself (with smaller arguments)

  22. length Defined base case recursive step

  23. append Defined 33

  24. member Defined mem? is a predicate (a test function) mem is the wrong name

  25. 7. Higher Order Functions • A higher order function has 1 or more arguments which are function names • higher order functions are also called functionals • Higher order functions are very important to advanced functional programming and AI.

  26. apply • (apply f x) • its first argument, f, is a function name • its second argument, x, is the input for f • same as executing (f x)

  27. map • (map f x) • returns a list by applying the function f to each element of the list x

  28. map and plusList plusList is applied to the 4 lists in the input list.

  29. More on Scheme

  30. Input and output • read - returns the input from the keyboard > (read) 234 ; user types this 234 ; the read function returns this > (+ 2 (read)) 3 ; user input 5 ; result • display - prints its single parameter to the screen > (display "hello world") hello world > (define x 2 ) >(display x) 2 • newline - displays a new line

  31. Input and output • Define a function that asks for input: (define (ask-them str) (display str) (read)) > (ask-them "How old are you? ") How old are you? 22 22

  32. Local definition • let - has a list of bindings and a body • each binding associates a name to a value • bindings are local (visible only in the body of let) • let returns the last expression in the body > (let ((a 2) (b 3)) ; list of bindings (+ a b)) ; body - expression to evaluate 5 > (+ a b) => error > a => Error: variable a is not bound. > b => Error: variable b is not bound. Notice the scope of a and b is within the body of let.

  33. Let • Factor out commonsub-expressions: f(x,y) = x(1+xy)2 + y(1-y) + (1+xy)(1-y) a = 1+xy b = 1-y f(x,y) = xa2 + yb + ab • Locally define the common sub-expressions: (define (f x y) (let ((a (+ 1 (* x y))) (b (- 1 y))) (+ (* x a a) (* y b) (* a b)))) (f 1 2) => 4

  34. ‘let’ can define functions • (let ((f +))   (f 2 3))  =>  5 • (let ((f +) (x 2)) (f x 3)) => 5 • (let ((f +) (x 2) (y 3))  (f x y))  =>  5 • The variables bound by let are visible only within the body of the let • (let ((+ *))  (+ 2 3))    6 (+ 2 3)    => 5

  35. Recursive definition • Example: define factorial factorial (n) = 1 * 2 * 3 * ...(n-1) * n factorial (n-1) 1 if n=1 (the base case) factorial(n) = n * factorial(n-1) otherwise (inductive step)

  36. Factorial example (define (factorial n) (if (= n 1) 1 (* n (factorial (- n 1))))) (factorial 4) => 24

  37. Fibonacci example • Fibonacci: 0 if n = 0 fib(n) =1 if n = 1 fib(n-1) + fib(n-2) otherwise • Implement in Scheme: (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2))))))

  38. Length example • Length of a list: 0 if list is empty len(lst) =1 + len( lst-without-first-element ) otherwise • Implement in Scheme: (define (len lst) (if (null? lst) 0 (+ 1 (len (cdrlst))))) |(length (a b c d))| (length (b c d))| |(length (c d))| | (length (d))| | |(length ())| | |0| | 1| |2| 3|4

  39. Sum example • Sum of elements in a list of numbers: (sum ‘(1 2 3)) => 6 0 if list is empty sum(lst) = first-element + sum (lst-without-first-element) otherwise • Implement in Scheme: (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdrlst)))))

  40. 9. Using DrScheme • Installation for Windows • called PLT Scheme Racket

  41. Start DrScheme from the Windows Start menu item PLT Scheme: definitions go here execute functions here

  42. Some Notes • Set the language mode to “Beginning Student with List Abbreviations” • under the Language > Choose Language menu item continued

  43. Press the "Run" button after adding a new function to the definitions window • this makes the new function visible down in the execution window

  44. Create a Scheme Program using any text editor

  45. Load myMax.scm use the File/Open menu item Press the "Run" button for the execution window to appear at thebottom.

  46. Use the myMax Function

  47. Alternatively, you can type the function into DrScheme's definition window, and save it from there. • you get colour-coded syntax, indenting (tabbing), and error checking as you type

  48. PLT Scheme  Racket • PLT Scheme v.5 was renamed to be called Racket • two websites: • http://plt-scheme.org/ (frozen in 2010) • http://racket-lang.org/ (active) • At the beginner's level, there's no difference between the two languages.

More Related