Utilitarian Programming in Scheme CS331 Chapter 10
Slide 2Functional Programming Online course reading: http://www.htdp.org/Original useful dialect is LISP LISt Processing The rundown is the central information structure Developed by John McCarthy in the 60's Used for typical information preparing Example applications: typical figurings in fundamental and differential analytics, circuit plan, rationale, diversion playing, AI As we will see the sentence structure for the dialect is amazingly basic Scheme Descendant of LISP
Slide 3Functional Languages "Immaculate" useful dialect Computation saw as a scientific capacity mapping contributions to yields No thought of state, so no requirement for task articulations (reactions) Iteration achieved through recursion In reasonableness LISP, Scheme, other useful dialects additionally bolster cycle, task, and so forth. We will cover some of these "tainted" components yet accentuate the useful segment Equivalence Functional dialects equal to basic Core subset of C can be executed decently clearly in Scheme itself actualized in C Church-Turing Thesis
Slide 4Lambda Calculus Foundation of practical programming Developed by Alonzo Church, 1941 A lambda expression characterizes Function parameters Body Does NOT characterize a name; lambda is the anonymous capacity. Underneath x characterizes a parameter for the anonymous capacity:
Slide 5Lambda Calculus Given a lambda expression Application of lambda expression Identity Constant 2:
Slide 6Lambda Calculus Any identifier is a lambda expression If M and N are lambda expressions, then the utilization of M to N , (MN) is a lambda expression A deliberation, composed where x is an identifier and M is a lambda expression, is additionally a lambda expression
Slide 7Lambda Calculus Examples
Slide 8Lambda Calculus First Class Citizens Functions are top of the line natives Can be returned as an esteem Can be passed as a contention Can be put into an information structure as an esteem Can be the estimation of an expression (( λ x·( λ y·x+y)) 2 1) = (( λ y·2+y) 1) = 3
Slide 9Lambda Calculus Functional writing computer programs is basically a connected lambda math with inherent -steady values -capacities E.g. in Scheme, we have (* x) for x*x rather than λ x·x*x
Slide 10Functional Languages Two approaches to assess expressions Eager Evaluation or Call by Value Evaluate all expressions early Irrespective of in the event that it is required or not May bring about some runtime blunders Example (foo 1 (/1 x)) Problem; partition by 0
Slide 11Lambda Calculus Lazy Evaluation Evaluate all expressions just if necessary (foo 1 (/1 x)) ; (/1 x) not required, so never eval'd Some assessments might be copied Equivalent to call-by-name Allows a few sorts of calculations impractical in energetic assessment Example Infinite records E.g,. Unbounded stream of 1's, whole numbers, even numbers, and so on. Replaces tail recursion with sluggish assessment call Possible in Scheme utilizing (constrain/delay)
Slide 12Running Scheme for Class An adaptation of Scheme called Racket (in the past PLT/Dr Scheme) is accessible on the Windows machines in the CS Lab Download: http://racket-lang.org/Unix, Mac forms likewise accessible if coveted
Slide 13Racket You can sort code specifically into the mediator and Scheme will come back with the outcomes:
Slide 15Make beyond any doubt right Language is chosen I jump at the chance to utilize the "Entirely Big" dialect decision
Slide 16Racket – Loading Code You can open code spared in a document. Racket utilizes the expansion ".rkt" so consider the accompanying document "factorial.rkt" made with a word processor or spared from Racket: 2: Run 1: Open (characterize factorial (lambda (n) (cond ((= n 1) 1) (else (* n (factorial (- n 1)))) ) 3: Invoke capacities
Slide 17Functional Programming Overview Pure utilitarian programming No certain thought of express No requirement for task proclamation No reaction Looping No state variable Use Recursion Most useful programming dialects have symptoms, including Scheme Assignments Input/Output
Slide 18Scheme Programming Overview Refreshingly basic Syntax is found out in around 10 seconds Surprisingly intense Recursion Functions as five star items (can be estimation of an expression, go as a contention, put in an information structure) Implicit stockpiling administration (refuse gathering) Lexical perusing Earlier LISPs did not do that (alterable) Interpreter Compiled variants accessible as well
Slide 19Expressions Syntax - Cambridge Prefix Parenthesized (* 3 4) (* (+ 2 3) 5) (f 3 4) when all is said in done: (functionName arg1 arg2 … ) Everything is an expression Sometimes called s-expr (typical expr)
Slide 20Expression Evaluation Replace images with their ties Constants assess to themselves 2, 44, #f No nil in Racket; utilize '() Nil = exhaust list, yet Racket has discharge Lists are assessed as capacity calls written in Cambridge Prefix documentation (+ 2 3) (* (+ 2 3) 5)
Slide 21Scheme Basics Atom Anything that can't be deteriorated encourage a series of characters starting with a letter, number or uncommon character other than ( or ) e.g. 2, #t, #f, "hi", foo, bar #t = genuine #f = false List A rundown of iotas or expressions encased in () (), empty,(1 2 3), (x (2 3)), (()()())
Slide 22Scheme Basics S-expressions Atom or rundown () or exhaust Both molecule and a rundown Length of a rundown Number at the top level
Slide 23Quote If we need to speak to the exacting rundown (a b c) Scheme will translate this as apply the contentions b and c to work a To speak to the strict rundown utilize "cite" (cite x) x (cite (a b c)) (a b c) Shorthand: single quote 'a == (cite an) '(a b c) == (cite (a b c))
Slide 24Global Definitions Use characterize work (characterize f 20) (characterize levels '(0 2 4 6 8)) (characterize chances '(1 3 5 7 9)) (characterize shading 'red) (characterize shading blue) ; Error, blue vague (characterize num f) ; num = 20 (characterize num 'f) ; image f (characterize s "hi world") ; String
Slide 25Lambda capacities Anonymous capacities (lambda (<formals>) <expression>) (lambda (x) (* x)) ((lambda (x) (* x)) 5) 25 Motivation Can make works as required Temporary capacities : don't need to have names Can not utilize recursion
Slide 26Named Functions Use characterize to tie a name to a lambda expression (characterize square (lambda (x) (* x))) (square 5) Using lambda all the time gets dull; substitute language structure: (characterize (<function name> <formals>) <expression1> <expression2> … ) Last expression assessed is the one returned (characterize (square x) (* x)) (square 5) 25
Slide 27Conditionals (if <predicate> <expression1> <expresion2>) -Return esteem is either expr1 or expr2 (cond (P1 E1) (P2 E2) (P n E n ) (else E n+1 )) -Returns whichever expression is assessed
Slide 28Common Predicates Names of predicates end with ? Number? : checks if the contention is a number Symbol? : checks if the contention is an image Equal? : checks if the contentions are fundamentally equivalent Null? : checks if the contention is vacant Atom? : checks if the contention is an iota Appears vague in Racket yet can characterize ourselves List? : checks if the contention is a rundown
Slide 29Conditional Examples (if (break even with? 1 2) 'x 'y) ; y (if (rise to? 2) 'x 'y) ; x (if (invalid? '()) 1 2) ; 1 (cond ((equal? 1 2) 1) ((equal? 2 3) 2) (else 3)) ; 3 (cond ((number? 'x) 1) ((null? 'x) 2) ((list? '(a b c)) (+ 2 3)) ; 5 )
Slide 30Dissecting a List Car : gives back the principal contention (auto '(2 3 4)) (auto '((2) 4)) Defined just for non-invalid records Cdr : (articulated "could-er") gives back whatever is left of the rundown Racket: list must have no less than one component Always gives back a rundown (cdr '(2 3 4)) (cdr '(3)) (cdr '(((3)))) Compose (auto (cdr '(4 5))) (cdr (auto '((3 4))))
Slide 31Shorthand (cadr x) = (auto (cdr x)) (cdar x) = (cdr (auto x)) (caar x) = (auto x)) (cddr x) = (cdr x)) (cadar x) = (auto (cdr (auto x))) … and so on… up to 4 levels somewhere down in Racket (cddadr x) = ?
Slide 32Why Car and Cdr? Extra documentation from unique execution of Lisp on an IBM 704 CAR = Contents of Address some portion of Register Pointed to the principal thing in the present rundown CDR = Contents of Decrement some portion of Register Pointed to whatever remains of the rundown
Slide 33Building a rundown Cons Cons(truct) another rundown from first and rest Takes two contentions Second ought to be a rundown If it is not, the outcome is a "specked combine" which is commonly viewed as a contorted rundown First might possibly be a rundown Result is dependably a rundown
Slide 34Building a rundown X = 2 and Y = (3 4 5) : (cons x y) (2 3 4 5) X = () and Y =(a b c) : (cons x y) (() a b c) X = an and Y =() : (cons x y ) (a) What is (cons 'a (cons 'b (cons 'c '()))) (cons 'a (cons 'b '())) (cons 'c '()))
Slide 35Numbers Regular number-crunching administrators are accessible +, - , *,/May take variable contentions (+ 2 3 4), (* 4 5 9 11) (/9 2) 4.5 ; (remainder 9 2) 4 Regular examination administrators are accessible < > <= >= = E.g. (= 5 (+ 3 2)) #t = just takes a shot at numbers, generally utilize square with?
Slide 36Example Sum all numbers in a rundown (characterize (sumall list) (cond ((invalid? list) 0) (else (+ (auto list) (sumall (cdr list)))))) Sample summon: (sumall '(3 45 1))
Slide 37Example Make a rundown of n indistinguishable qualities (characterize (makelist n esteem) (cond ((= n 0) '()) (else (cons esteem (makelist (- n 1) esteem)) ) In longer projects, cautious coordinating enclosure.
Slide 38Example Determining if a thing is an individual from a rundown (characterize (part? thing list) (cond ((invalid? list) #f)
SPONSORS
SPONSORS
SPONSORS