Scope and Introduction to Functional Languages Prof. Evan Chang Meeting 7, CSCI 3155, Fall 2009 Announcements Assignment 3 due Thu at 11:55pm Submit in pairs Website has SML resources Text: Harper, Programming in SML Supplemental Text: Hansen and Rischel, Introduction to Programming using SML (on reserve) SML is installed on CSEL 2 Static scoping: Let s extend arithmetic with a binding construct e ::= n e 1 + e 2 e 1 * e 2 let x = e 1 in e 2 x Review and Finish Scoping let binds a new variable x to e 1 for use in e 2 variable x is bound in the body e 2 the scope of x is the body e 2 4 How do resolve variables? Lexical scope rule: A variable is bound by the nearest enclosing binding Operationally, we walk up through the AST looking for the nearest let that binds that variable Can we do a program transformation to make it clear where a variable is bound? How? 5 6 1
Rename bound variables Examples We identify terms up to renaming (αconversion) Higher-Order Abstract Syntax: All terms that differ only in names of bound variables are considered equivalent. 7 8 Free Variables A free variable of an expression e is a variable that is not bound within e Define fv(e) - set of free vars of e fv( var(x) ) = { x } fv( num(n) ) = fv( plus(e 1, e 2 ) ) = fv( times(e 1, e 2 ) ) = fv( let(x, e 1, e 2 ) ) = Variable Renaming Define [y/x]e to be the renaming of all free occurrences of x to y in e [y/x]var(z) = [y/x]num(n) = [y/x]plus(e 1, e 2 ) = [y/x]times(e 1, e 2 ) = [y/x]let(z, e 1, e 2 ) = 9 10 α-conversion An equivalence relation given by the following axiom: let(x, e 1, e 2 ) let(y, e 1, [y/x]e 2 ) In any context (formally, a congruence) 11 2
Dynamic Scoping Scope depends on the calling sequence of functions Within a function, is there any difference with static scoping? Exercise: Which x is used? PROCEDURE f() = VAR x : INTEGER; PROCEDURE g() = VAR x : INTEGER; BEGIN END; PROCEDURE h() = BEGIN x END; BEGIN h(); g(); END BEGIN g(); h(); END 13 14 Summary: Dynamic Scoping No variable is local making programs difficult to debug e.g., in LISP, TCL, TeX On to Functional Languages Generally, considered a bug in PL implementation (but watch out, very easy to do!) 15 Functional Programming You know OO and Imperative Functional Programming Computation = evaluating (math) functions Avoid global state and mutable data Get stuff done = apply (higher-order) functions Important Features Higher-order, first-class functions Closures and recursion Symbolic processing (lists, ASTs) Computation In a pure functional language, computation is simply expression evaluation fun add (x,y) = if x=0 then y else add(x-1,y+1) add(2,5) 17 18 3
State Imperative programs destructively modify existing state Functional programs yield new similar states over time SET1 SET add_elem(set, item) add_elem(set1, item) SET2 19 Functional Example Simple Functional Set (built out of lists) fun add_elem (s, e) = if s = [] then [e] else if hd s = e then s else hd s :: add_elem(tl s, e) Pattern-Matching Functional fun add_elem ([],e) = [e] add_elem (hd :: tl, e) = if hd = e then s else hd :: add_elem(tl,e) 20 In Imperative Code Functional-Style Advantages More cases to handle List* add_elem(list *s, item e) { if (s == NULL) return list(e, NULL); else if (s->hd == e) return s; else if (s->tl == NULL) { I have stopped reading Stephen King novels. Now I just read C code instead. - Richard O Keefe s->tl = list(e, NULL); return s; } else return add_elem(s->tl, e); } 21 Tractable program semantics Procedures are functions Formulate and prove assertions about code More readable Referential transparency What is it? 22 Functional-Style Advantages Tractable program semantics Procedures are functions Formulate and prove assertions about code More readable Referential transparency Replace any (sub)expression by its value without changing the result How do functional languages give you referential transparency? 23 24 4
No side-effects Functional-Style Disadvantages? Why is referential transparency useful? 25 26 Functional-Style Disadvantages Efficiency Copying takes time (if needed) Compiler implementation Frequent memory allocation Unfamiliar (to you!) New programming style Not appropriate for every program Operating systems, etc. SML 27 Short History ML (Meta Language) Edinburgh, 1973 Part of a theorem proving system LCF SML/NJ (Standard ML of New Jersey) Bell Labs and Princeton, 1990 OCaml (Objective Caml) INRIA, 1996 Same core ideas but some (annoying) syntactic differences 29 ML Innovative Features Type system Strongly typed Type inference Abstraction Modules Patterns Polymorphism Higher-order functions Concise formal semantics There are many ways of trying to understand programs. People often rely too much on one way, which is called debugging and consists of running a partly-understood program to see if it does what you expected. Another way, which ML advocates, is to install some means of understanding in the very programs themselves. - Robin Milner, 1997 30 5
A Small SML Program SML Top-Level Value and function declarations (* *) for comments (nestable) (* A small SML program *) val four = 4 fun plusfour y = y + four val eight = plusfour four; Interactive loop: expressions can be typed and evaluated at the top-level Standard ML of New Jersey v110.65 [built: Wed Oct 31 17:24:44 2007] - 1; val it = 1 : int No type declarations needed! ; ends top-level expressions, not needed with just declarations 31 Run a file by typing use file.sml ; 32 Simple SML Examples: Basic Types For Next Time Reading (a bit longer than usual) Online discussion forum 1 substantive question, comment, or answer each week Homework assignment 3 Acknowledgments: Wes Weimer (functional vs. imperative examples) 33 34 6