Compiler construction in4020 – lecture 13 Koen Langendoen Delft University of Technology The Netherlands.

Slides:



Advertisements
Similar presentations
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 14 Functional Programming It is better to.
Advertisements

Kathleen Fisher cs242 Reading: “Concepts in Programming Languages”, Chapter 6.
Introduction to Compilation of Functional Languages Wanhe Zhang Computing and Software Department McMaster University 16 th, March, 2004.
1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Compiler construction in4020 – lecture 4 Koen Langendoen Delft University of Technology The Netherlands.
Compiler construction in4020 – lecture 10 Koen Langendoen Delft University of Technology The Netherlands.
© M. Winter COSC 4P41 – Functional Programming Testing vs Proving Testing –uses a set of “typical” examples, –symbolic testing, –may find errors,
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Compiler construction in4020 – lecture 12 Koen Langendoen Delft University of Technology The Netherlands.
Memory Management Professor Yihjia Tsai Tamkang University.
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions Most of this should be review for you.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 14 Functional Programming It is better to.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
CSC321: Programming Languages14-1 Programming Languages Tucker and Noonan Chapter 14: Functional Programming 14.1 Functions and the Lambda Calculus 14.2.
Sparkle A theorem prover for the functional language Clean Maarten de Mol University of Nijmegen February 2002.
Compiler Summary Mooly Sagiv html://
Comp 205: Comparative Programming Languages Lazy Evaluation Errors Evaluation Strategies Infinite Lists…. Lecture notes, exercises, etc., can be found.
Functional Programming Professor Yihjia Tsai Tamkang University.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
Functional Programming in Haskell Motivation through Concrete Examples Adapted from Lectures by Simon Thompson.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
1 SML fn x => e e 1 e 2 0, 1, 2,..., +, -,... true, false, if e then e else e patterns datatypes exceptions structures functors fun f x = e variables.
Functional Languages. Why? Referential Transparency Functions as first class objects Higher level of abstraction Potential for parallel execution.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
ISBN Chapter 15 Functional Programming Languages.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Runtime Environments. Support of Execution  Activation Tree  Control Stack  Scope  Binding of Names –Data object (values in storage) –Environment.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
11/1/20151 GC16/3011 Functional Programming Lecture 5 Miranda patterns, functions, recursion and lists.
Chapter Fifteen: Functional Programming Languages Lesson 12.
Compiling Functional Programs Mooly Sagiv Chapter 7
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
COMP313A Functional Programming (1)
CS535 Programming Languages Chapter - 10 Functional Programming With Lists.
CSE 425: Control Abstraction I Functions vs. Procedures It is useful to differentiate functions vs. procedures –Procedures have side effects but usually.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
1 Haskell Kevin Atkinson John Simmons. 2 Contents Introduction Type System Variables Functions Module System I/O Conclusions.
CS5205Introduction1 CS5205: Foundation in Programming Languages Lecture 0 : Overview Lecturer : Chin Wei Ngan Office : COM2.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
CS5205Haskell1 CS5205: Foundation in Programming Languages Basics of Functional Programming.
CSE 5317/4305 L12: Higher-Order Functions1 Functional Languages and Higher-Order Functions Leonidas Fegaras.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Haskell Introduction CSCE 314 Spring CSCE 314 – Programming Studio Historical Background 1930s: Alonzo Church develops the lambda calculus, a simple.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
Ch Ch jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (n-n-n-notes) Summer 2003 Dr. Carter Tiernan.
Runtime Environments Chapter 7. Support of Execution  Activation Tree  Control Stack  Scope  Binding of Names –Data object (values in storage) –Environment.
1 PROGRAMMING IN HASKELL An Introduction Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Functional Programming
CS314 – Section 5 Recitation 9
Functional Programming
A lightening tour in 45 minutes
Functional Programming
Higher-Order Procedures
FP Foundations, Scheme In Text: Chapter 14.
Presentation transcript:

Compiler construction in4020 – lecture 13 Koen Langendoen Delft University of Technology The Netherlands

Summary of lecture 12 Memory management manual malloc() + free() garbage collection reference counting mark & sweep two-space copying A C D E B heap root set B B E E F

Quiz 5.9 The pointer assignment p := q is han- dled by first incrementing the reference count of q before decrementing that of p What goes wrong if the order is reversed? Increment q.ref count; Decrement p.ref count; IF p.ref count = 0: Free recursively (p); SET p TO q; ??

Poll results lectures: practicum: suggestions: fun assignments poor documentation lot of work! minavgmax CS EE improve docs: LLgen Asterix sources assignment 2

languages: LISP, scheme, ML, Miranda, Haskell features: high abstraction level: what vs how, where, when equational reasoning functions as first class citizens Functional programming languages: LISP, Scheme, ML, Miranda, Haskell features: compiler must work harder!!

Overview of a typical functional compiler high-level language (Haskell) functional core Cruntime system + optimizations desugaring type inference code generation

Function application concise notation precedence over all other operators HaskellC f 11 13f(11, 13) f n+1f(n) + 1

offside rule list notation pattern matching list comprehension offside rule: end-of-equation marking list notation pattern matching list comprehension offside rule list notation: pattern matching list comprehension [] [1,2,3] (1:(2:(3:[]))) offside rule list notation pattern matching: case analysis of arguments list comprehension Syntactic sugar qsort [] = [] qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y = x] offside rule list notation pattern matching list comprehension: mathematical sets

Polymorphic typing an expression is polymorphic if it ‘has many types’ examples length [] = 0 length (x:xs) = 1 + length xs empty list: [ ] list handling functions length :: [a] -> Int length [] = 0 length (x:xs) = 1 + length xs

Polymorphic type inference map f [] = [] map f (x:xs) = f x : map f xs map :: t 1 -> t 2 -> t 3 map f [] = [] map :: t 1 -> [a] -> [b] map f (x:xs) = f x : map f xs x :: a f :: a -> b map :: (a -> b) -> [a] -> [b]

Exercise (5 min.) infer the polymorphic type of the following higher-order function: filter f [] = [] filter f (x:xs) = if not(f x) then filter f xs else x : (filter f xs)

Answers

filter f [] = [] filter f (x:xs) = if not(f x) then filter f xs else x : (filter f xs) Answers filter :: t 1 -> t 2 -> t 3 filter f [] = [] filter :: t 1 -> [a] -> [b] x :: a f :: a -> Bool filter :: (a -> Bool) -> [a] -> [a] filter f (x:xs) = if not(f x) then filter f xs else x : (filter f xs)

Referential transparency f x always denotes the same value advantage: high-level optimization is easy disadvantage: no efficient in-place update g (f x) (f x) let a = f x in g a a add_one [] = [] add_one (x:xs) = x+1 : add_one xs

Higher-order functions functions are first-class citizens higher-order functions accept functions as parameters and/or return a function as result functions may be created “on the fly” D f = f where f (x) = lim h  0 f(x+h) – f(x) h diff f = f_ where f_ x = (f (x+h) – f x)/h h =

Currying: specialize functions Q: diff (unary function)  deriv (binary function)? deriv f x = (f (x+h) – f x)/h where h = diff f = f_ where f_ x = (f (x+h) – f x)/h h =  f,  x (diff f) x = deriv f x A: yes! binary function  a unary function returning a unary function f e 1 … e n  ( n f e 1 ) … e n ) (deriv square) is a curried function

Lazy evaluation An expression will only evaluated when its value is needed to progress the computation additional expressive power (infinite lists) overhead for delaying/resuming computations nats = [1..] squares = [x^2 | x <- nats] main = take 100 squares ones = 1 : ones deriv f x = lim [(f (x+h) – f x)/h | h <- downto 0] where downto x = [x + 1/2^n | n <- [1..]] lim (a:b:lst) = if abs (a/b – 1) < eps then b else lim (b:lst)

Break

Structure of a typical functional compiler high-level language (Haskell) functional core Cruntime system + optimizations desugaring type inference code generation

Graph reduction implement h.o.f + lazy evaluation key: function application f e 1 … e n  ( n f e 1 ) e 2 ) … e n ) execution (interpretation) build graph for main expression find reducible expression (redex  func + args) instantiate body (build graph for    enen ( n e 1 e 2 ) e n )

Example let twice f x = f (f x) square n = n*n in twice square @ 3 * square3 * *

Reduction order a graph may contain multiple redexes lazy evaluation: choose built-in operators (+,-,*, etc) may have strict arguments that must be evaluated => recursive 3

Implementation typedef struct node *Pnode; extern Pnode eval( Pnode root); argument stack Graph reduction – three stroke engine find next redex instantiate rhs update root unwind application spine (f a 1 …a n ) Pnode mul(Pnode arg[]) { Pnode a = eval(arg[0]); Pnode b = eval(arg[1]); return Num(a->nd.num * b->nd.num); } update root with result call f, pass arguments in array (stack)

Code generation average a b = (a+b) / 2 Pnode average(Pnode arg[]) { Pnode a = arg[0]; Pnode b = arg[1]; return Appl(Appl(fun_div, Appl(Appl(fun_add,a),b)), Num(2)); } a

Short-circuiting application spines average a b = (a+b) / 2 Pnode average(Pnode arg[]) { Pnode a = arg[0]; Pnode b = arg[1]; return Appl(Appl(fun_div, Appl(Appl(fun_add,a),b)), Num(2)); } call leftmost outermost function directly Pnode average(Pnode arg[]) { Pnode a = arg[0]; Pnode b = arg[1]; return div(Appl(Appl(fun_add,a),b), Num(2)); } a

call leftmost outermost function directly Pnode average(Pnode arg[]) { Pnode a = arg[0]; Pnode b = arg[1]; return div(Appl(Appl(fun_add,a),b), Num(2)); } Strict arguments average a b = (a+b) / 2 evaluate expressions supplied to strict built-in functions immediately Pnode average(Pnode arg[]) { Pnode a = arg[0]; Pnode b = arg[1]; return div(add(a,b), Num(2)); } a

Strictness analysis user-defined functions: propagate sets of strict arguments up the AST foo x y = if x>0 then x*y else 0 if 0> x0 * xy {x}{} {x} {y} {x} {x,y}

Strictness propagation A i, if n  m fun A A n …… C  (T  E) if C then T else E L  RL  RL  RL  R propagated setlanguage construct  strict(fun,i) m i=1

Recursive functions foo x y = if x>0 then y else foo (x+1) y if > x0 * xy {x} {} foo y {x}{x,y} {}{x} {y} {x} + x1 {y} {x}{} problem: conservative estimation of strictness

Recursive functions foo x y = if x>0 then y else foo (x+1) y if > x0 * xy {x,y} foo y {x}{x,y} {}{x} {y} + x1 {x}{y} {x}{} solution: optimistic estimation of strictness iterate until result equals assumption (+,+)

Exercise (6 min.) infer the strict arguments of the following recursive function: how many iterations are needed? g x y 0 = x g x y z = g y x (z-1)

Answers stepassumptionresult

Answers g x y 0 = x g x y z = g y x (z-1) g x y z = if z == 0 then x else g y x (z-1) 4 {z} 3 {x,z} 2 {x,y,z} 1 resultassumptionstep

Summary Haskell featurecompiler phase offside rulelexical analyzer list notation list comprehension pattern matching parser polymorphic typingsemantic analyzer referential transparency higher-order functions lazy evaluation run-time system (graph reducer)

The end

TODO assignment 2: make Asterix OO deadline June 4 08:59 study book chapter 1 – 7, except make appointment by for oral exam 30 min per group