COMS W4115 Programming Languages & Translators Maria Ayako Taku COMS W4115 - PLT Columbia University 1 April 24, 2013 Functional Programming.

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
1 JavaCUP JavaCUP (Construct Useful Parser) is a parser generator Produce a parser written in java, itself is also written in Java; There are many parser.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
1 Pass Compiler 1. 1.Introduction 1.1 Types of compilers 2.Stages of 1 Pass Compiler 2.1 Lexical analysis 2.2. syntactical analyzer 2.3. Code generation.
Compiler Construction
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap  Syntax and Semantics  Semantics of Expressions 
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
ML-YACC David Walker COS 320. Outline Last Week –Introduction to Lexing, CFGs, and Parsing Today: –More parsing: automatic parser generation via ML-Yacc.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 14 Functional Programming It is better to.
Environments and Evaluation
CSC321: Programming Languages14-1 Programming Languages Tucker and Noonan Chapter 14: Functional Programming 14.1 Functions and the Lambda Calculus 14.2.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Chapter 7Louden, Programming Languages1 Chapter 7 - Control I: Expressions and Statements "Control" is the general study of the semantics of execution.
PPL Syntax & Formal Semantics Lecture Notes: Chapter 2.
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
Haskell Chapter 1, Part I. Highly Recommended  Learn you a Haskell for Great Good. Miran Lipovaca.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Functional Languages. Why? Referential Transparency Functions as first class objects Higher level of abstraction Potential for parallel execution.
CSE S. Tanimoto Lambda Calculus 1 Lambda Calculus What is the simplest functional language that is still Turing complete? Where do functional languages.
1 Top Down Parsing. CS 412/413 Spring 2008Introduction to Compilers2 Outline Top-down parsing SLL(1) grammars Transforming a grammar into SLL(1) form.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
CMSC 330: Organization of Programming Languages
COMP Parsing 3 of 4 Lectures 23. Using the Scanner Break input into tokens Use Scanner with delimiter: public void parse(String input ) { Scanner.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Functional Programming Language OCaml Tutorial 科大 - 耶鲁联合研究中心
Compiling Functional Programs Mooly Sagiv Chapter 7
CPS 506 Comparative Programming Languages Syntax Specification.
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
Chapter 1 Introduction Study Goals: Master: the phases of a compiler Understand: what is a compiler Know: interpreter,compiler structure.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Introduction CPSC 388 Ellen Walker Hiram College.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Fall 2008Programming Development Techniques 1 Topic 17 Assignment, Local State, and the Environment Model of Evaluation Section 3.1 & 3.2.
1 Structure of Compilers Lexical Analyzer (scanner) Modified Source Program Parser Tokens Semantic Analysis Syntactic Structure Optimizer Code Generator.
Classes, Interfaces and Packages
CMSC 330: Organization of Programming Languages Operational Semantics.
Compiler Construction CPCS302 Dr. Manal Abdulaziz.
LECTURE 3 Compiler Phases. COMPILER PHASES Compilation of a program proceeds through a fixed series of phases.  Each phase uses an (intermediate) form.
CS412/413 Introduction to Compilers and Translators April 2, 1999 Lecture 24: Introduction to Optimization.
Haskell Introduction CSCE 314 Spring CSCE 314 – Programming Studio Historical Background 1930s: Alonzo Church develops the lambda calculus, a simple.
CSE 425: Functional Programming I Programs as Functions Some programs act like mathematical functions –Associate a set of input values from the function’s.
Overview of Compilation Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Programming Language Principles Lecture 2.
6/21/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman,
Functional Programming
Operational Semantics of Scheme
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment
6.001 SICP Variations on a Scheme
Chapter 7: Expressions and Assignment Statements
PROGRAMMING LANGUAGES
CS 536 / Fall 2017 Introduction to programming languages and compilers
Functional Programming
CSE 3302 Programming Languages
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
FP Foundations, Scheme In Text: Chapter 14.
Compiler Construction
The Recursive Descent Algorithm
6.001 SICP Interpretation Parts of an interpreter
CSE S. Tanimoto Lambda Calculus
topics interpreters meta-linguistic abstraction eval and apply
Compiler Construction
CSE341: Programming Languages Lecture 12 Equivalence
Presentation transcript:

COMS W4115 Programming Languages & Translators Maria Ayako Taku COMS W PLT Columbia University 1 April 24, 2013 Functional Programming Languages and the Influence of Lambda Calculus Lecture 23

Why Functional Programming? COMS W PLT Columbia University 2 April 24, 2013 You may have heard that: (1)functional programs are very succinct and elegant, but… (2) they take forever to write and understand let xor p = match p with (false, x) -> x | (true, x) -> not x;; let xor p = match p with (false, x) -> x | (true, x) -> not x;; Simple XOR program:

Outline COMS W PLT Columbia University 3 April 24, 2013 I.What is Functional Programming? II.Lambda Calculus' Influence on Functional Programming III.Benefits of Functional Programming IV.OCaml in Action: An Entire Interpreter in 3 slides

What is Functional Programming? COMS W PLT Columbia University 4 April 24, 2013 A "programming paradigm" that focuses on the evaluation of functions Programs are defined as recursive functions, where each takes a single input and outputs a single result. Recall lambda calculus nests functions in this manner. Ex: (+ (* 1 2) (- 4 3)) let f = let a = 1*2 in let b = 4-3 in a + b;; let f = let a = 1*2 in let b = 4-3 in a + b;; In OCaml:

What is Functional Programming? COMS W PLT Columbia University 5 April 24, 2013 One important trademark of Functional Programming: It avoids both changes in state and mutable data These expressions are not equal. Conceptually, they are more like this. //F#//C# let a=42; int a=42; //F#//C# let a=42;static int a(){ return 42; }

What is Functional Programming? COMS W PLT Columbia University 6 April 24, 2013 Some Common (more or less) FP Languages: LISP OCaml Haskell Erlang F# (multi-paradigm) So what's the value in functional programming? Are its benefits worth taking the time to learn it and overcoming the (possibly) steep learning curve?

Outline COMS W PLT Columbia University 7 April 24, 2013 I.What is Functional Programming? II.Lambda Calculus' Influence on Functional Programming III.Benefits of Functional Programming IV.OCaml in Action: An Entire Interpreter in 3 slides

Lambda Calculus' Influence COMS W PLT Columbia University 8 April 24, 2013 The syntax and theory of Functional Programming is highly influenced by lambda calculus. Knowledge of lambda calculus means that FP is easier to learn, understand, and use efficiently. You might recognize some of the following FP syntax traits from lambda calculus…

Lambda Calculus' Influence Function Abstraction COMS W PLT Columbia University 9 April 24, 2013 Lambda Calculus Recap A function abstraction consists of four parts: 1.a lambda followed by 2.a single variable, 3.a period, and then 4.an expression λx.expr

Lambda Calculus' Influence Function Abstraction COMS W PLT Columbia University 10 April 24, 2013 λx.expr Lambda Calculus: fun x -> expr;; OCaml: f(x) = expr Algebra:

Lambda Calculus' Influence Function Abstraction COMS W PLT Columbia University 11 April 24, 2013 is equivalent to Named Functions: OCaml strays from pure functional programming at times. The "let" command can be used to allow one to create named functions fun x -> expr;; let myFunc x = expr;; The Let Command

Lambda Calculus' Influence Function Abstraction COMS W PLT Columbia University 12 April 24, 2013 # let fToc temp = (temp )/. 1.8;; # fToc 98.6;; - : float = # let fToc temp = (temp )/. 1.8;; # fToc 98.6;; - : float = double fToc (double temp) { return (temp-32)/1.8; } fToc(98.6); double fToc (double temp) { return (temp-32)/1.8; } fToc(98.6); An OCaml "let" example Similar code in Java

Lambda Calculus' Influence Beta Reductions COMS W PLT Columbia University 13 April 24, 2013 Lambda Calculus Recap A function application is evaluated via a beta reduction Which occurs when an actual value is substituted for a variable Examples: (λx.xzx)y → [y/x]xzx = yzy (λx.+ 1 x)7 → = 8 Layman's Terms: (λx.expr1)expr2 means "replace every instance of x in expr1 with expr2"

Lambda Calculus' Influence Beta Reductions COMS W PLT Columbia University 14 April 24, 2013 (λx.expr1)expr2 Lambda Calculus: (fun x ->expr1)expr2;; OCaml: (fun x ->x*x)5;; (* Evaluates to 5*5 = 25 *) (fun x ->x*x)5;; (* Evaluates to 5*5 = 25 *) Example Usage:

Lambda Calculus' Influence Beta Reductions COMS W PLT Columbia University 15 April 24, 2013 (fun x ->expr1)expr2;; let x = 5 in x*x;; (* Evaluates to 5*5=25*) let x = 5 in x*x;; (* Evaluates to 5*5=25*) Example Usage: The Let Command let x = expr2 in expr1;; Is semantically equivalent to: The "let" command can once again be used to perform similar functionality to the "fun" command.

Outline COMS W PLT Columbia University 16 April 24, 2013 I.What is Functional Programming? II.Lambda Calculus' Influence on Functional Programming III.Benefits of Functional Programming IV.OCaml in Action: An Entire Interpreter in 3 slides

Benefits of Functional Programming COMS W PLT Columbia University 17 April 24, 2013 A few benefits in a nutshell: 1.Succinct Code 2.Encourages disciplined and logical thinking 3.Lazy Evaluation 4.Higher Level Functions Example: List.fold_left (fun s e ->s + e) 0 [42; 17; 120];; 5.No Side Effects & Referential Transparency

Benefits of Functional Programming No Side Effects COMS W PLT Columbia University 18 April 24, 2013 Side Effect: a function or expression has a side effect if it modifies state or has an observable interaction with the "outside world." Examples: Modify global/static variables Modify arguments Write data to a display or file Functional programs contain no assignment statements. So variables, once given a value, never change.

Benefits of Functional Programming No Side Effects COMS W PLT Columbia University 19 April 24, 2013 Simple Side Effect Example in Java static int x = 5; static void changeX (int a){ x = a; } changeX(4); // This function has the side effect // of changing the value of global var x static int x = 5; static void changeX (int a){ x = a; } changeX(4); // This function has the side effect // of changing the value of global var x

Benefits of Functional Programming Referential Transparency COMS W PLT Columbia University 20 April 24, 2013 Referential Transparency: An expression (e.g., function) is referentially transparent if it always produces the same output for the same input. Lack of side effects results in referential transparency. Because of this behavior, a variable/expression can always be replaced with its value without changing the behavior of a program if that language has Referential Transparency.

Benefits of Functional Programming Referential Transparency COMS W PLT Columbia University 21 April 24, 2013 Lack of Referential Transparency in Java static int x = 10; static int add(int a){ return a + x; } add(1); // returns 11 x = 0; add(1); // returns 10, even though same input. NOT RT! static int x = 10; static int add(int a){ return a + x; } add(1); // returns 11 x = 0; add(1); // returns 10, even though same input. NOT RT!

Why are Referential Transparency and Lack of Side Effects Good? COMS W PLT Columbia University 22 April 24, 2013 Elimination of bugs Debugging in general is easier Independence of evaluation order Safe reuse of subprograms Safe multithreading

Why are Referential Transparency and Lack of Side Effects Good? COMS W PLT Columbia University 23 April 24, 2013 Easier to Compile – It's not only people that benefit from being able to better predict and understand a program's behavior Better Compiling – optimization via: – Memoization – Parallelization – Common Subexpression Elimination Easier and Better Compiling

Outline COMS W PLT Columbia University 24 April 24, 2013 I.What is Functional Programming? II.Lambda Calculus' Influence on Functional Programming III.Benefits of Functional Programming IV.OCaml in Action: An Entire Interpreter in 3 slides

Implementing an Interpreter in OCaml COMS W PLT Columbia University 25 April 24, 2013 We will build a simple desk calculator to perform integer arithmetic. You recall the basic block diagram of a simple interpreter: Lexer Parser AST Walker tokensAST Input (arithmetic expression) Output (evaluated arithmetic expression)

Implementing an Interpreter in OCaml COMS W PLT Columbia University 26 April 24, 2013 Courtesy of Stephen Edwards' PLT Lecture Slides: { open Parser } rule token = parse [’ ’ ’\t’ ’\r’ ’\n’] { token lexbuf } | ’+’ { PLUS } | ’-’{ MINUS } | ’*’ { TIMES } | ’/’ { DIVIDE } | [’0’-’9’]+ as lit { LITERAL (int_of_string lit) } | eof{ EOF } { open Parser } rule token = parse [’ ’ ’\t’ ’\r’ ’\n’] { token lexbuf } | ’+’ { PLUS } | ’-’{ MINUS } | ’*’ { TIMES } | ’/’ { DIVIDE } | [’0’-’9’]+ as lit { LITERAL (int_of_string lit) } | eof{ EOF } type operator = Add | Sub | Mul | Div type expr = Binop of expr * operator * expr | Lit of int type operator = Add | Sub | Mul | Div type expr = Binop of expr * operator * expr | Lit of int scanner.mll ast.mli

Implementing an Interpreter in OCaml COMS W PLT Columbia University 27 April 24, 2013 parser.mly %{ open Ast %} %token PLUS MINUS TIMES DIVIDE EOF %token LITERAL %left PLUS MINUS %left TIMES DIVIDE %start expr %type expr % %{ open Ast %} %token PLUS MINUS TIMES DIVIDE EOF %token LITERAL %left PLUS MINUS %left TIMES DIVIDE %start expr %type expr % expr: expr PLUS expr { Binop($1, Add, $3) } | expr MINUS expr { Binop($1, Sub, $3) } | expr TIMES expr { Binop($1, Mul, $3) } | expr DIVIDE expr { Binop($1, Div, $3) } | LITERAL { Lit($1) } expr: expr PLUS expr { Binop($1, Add, $3) } | expr MINUS expr { Binop($1, Sub, $3) } | expr TIMES expr { Binop($1, Mul, $3) } | expr DIVIDE expr { Binop($1, Div, $3) } | LITERAL { Lit($1) }

Implementing an Interpreter in OCaml COMS W PLT Columbia University 28 April 24, 2013 AST Walker: calc.ml open Ast let rec eval = function Lit(x) -> x | Binop (e1, op, e2) -> let v1 = eval e1 and v2 = eval e2 in match op with Add -> v1 + v2 | Sub -> v1 - v2 | Mul ->v1 * v2 | Div -> v1 / v2 let _ = let lexbuf = Lexing.from_channel stdin in let expr = Parser.expr Scanner.token lexbuf in let result = eval expr in print_endline (string_of_int result) open Ast let rec eval = function Lit(x) -> x | Binop (e1, op, e2) -> let v1 = eval e1 and v2 = eval e2 in match op with Add -> v1 + v2 | Sub -> v1 - v2 | Mul ->v1 * v2 | Div -> v1 / v2 let _ = let lexbuf = Lexing.from_channel stdin in let expr = Parser.expr Scanner.token lexbuf in let result = eval expr in print_endline (string_of_int result)

Quick Side Note: Pattern Matching in OCaml COMS W PLT Columbia University 29 April 24, 2013 Pattern Matching a Parameter (function…) Pattern Matching a Value (match…with) Main difference is how the pattern matcher receives its value to match function param1 -> expr1 | param2 -> expr2 | param3 -> expr3 function param1 -> expr1 | param2 -> expr2 | param3 -> expr3 match expr with param1 -> expr1 | param2 -> expr2 | param3 -> expr3 match expr with param1 -> expr1 | param2 -> expr2 | param3 -> expr3

Quick Side Note: Pattern Matching in OCaml COMS W PLT Columbia University 30 April 24, 2013 If you recall the XOR program from the beginning of this lecture, you should now be able to understand how this works. Hint: Variables, such as "x" will match anything and are bound to a value when the pattern matches. let xor p = match p with (false, x) -> x | (true, x) -> not x;; let xor p = match p with (false, x) -> x | (true, x) -> not x;;

Compiling the Interpreter COMS W PLT Columbia University 31 April 24, 2013 $ ocamllex scanner.mll # create scanner.ml 8 states, 267 transitions, table size 1116 bytes $ ocamlyacc parser.mly # create parser.ml and parser.mli $ ocamlc –c ast.mli # compile AST types $ ocamlc –c parser.mli # compile parser types $ ocamlc –c scanner.ml # compile the scanner $ ocamlc –c parser.ml # compile the parser $ ocamlc –c calc.ml # compile the interpreter $ ocamlc –o calc parser.cmo scanner.cmo calc.cmo $./calc 2 * * 5 26 $ $ ocamllex scanner.mll # create scanner.ml 8 states, 267 transitions, table size 1116 bytes $ ocamlyacc parser.mly # create parser.ml and parser.mli $ ocamlc –c ast.mli # compile AST types $ ocamlc –c parser.mli # compile parser types $ ocamlc –c scanner.ml # compile the scanner $ ocamlc –c parser.ml # compile the parser $ ocamlc –c calc.ml # compile the interpreter $ ocamlc –o calc parser.cmo scanner.cmo calc.cmo $./calc 2 * * 5 26 $

So Why Functional Programming? COMS W PLT Columbia University 32 April 24, 2013 It's hard to get to compile, but once it compiles, it works -Unknown PLT Student

References COMS W PLT Columbia University 33 April 24, 2013 Edwards, Stephen. “An Introduction to Objective Caml.” fall/ocaml.pdf Huges, John. “Why Functional Programming Matters.” Research Topics in Functional Programming, Addison- Wesley, 1990: pp “Advantages of Functional Programming.” ming