Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:

Slides:



Advertisements
Similar presentations
Types and Programming Languages Lecture 7 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Advertisements

Modern Programming Languages, 2nd ed.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Tim Sheard Oregon Graduate Institute Lecture 8: Operational Semantics of MetaML CSE 510 Section FSC Winter 2005 Winter 2005.
8. Introduction to Denotational Semantics. © O. Nierstrasz PS — Denotational Semantics 8.2 Roadmap Overview:  Syntax and Semantics  Semantics of Expressions.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Tim Sheard Oregon Graduate Institute Lecture 4: Staging Interpreters CSE 510 Section FSC Winter 2004 Winter 2004.
Compiler Construction
1 Meta-Programming through Typeful Code Representation Chiyan Chen and Hongwei Xi Boston University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Tim Sheard Oregon Graduate Institute Lecture 2: More on MetaML CS510 Sect FSC Winter 2004 Winter 2004.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Tim Sheard Oregon Graduate Institute Lecture 5: Review of homework 2 CS510 Sect FSC Winter 2004 Winter 2004.
Tim Sheard Oregon Graduate Institute CS510 Sect FSC Winter 2004 Winter 2004 Lecture 1: Introduction.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Tim Sheard Oregon Graduate Institute Lecture 11: A Reduction Semantics for MetaML CS510 Section FSC Winter 2005 Winter 2005.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
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,
CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Winter 2013.
Introduction and Chapter 8 of Programming Languages by Ravi Sethi Elements of Functional Programming.
Functional Programming Element of Functional Programming.
Staging in Haskell What is Staging What does it Mean Using Template Haskell.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Chapter 9: Functional Programming in a Typed Language.
Advanced Functional Programming Tim Sheard 1 Lecture 14 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Advanced Functional Programming Tim Sheard 1 Lecture 18 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture.
CSE 341 : Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Spring 2014.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Advanced Functional Programming Tim Sheard 1 Lecture 16 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Spring 2017.
Principles of programming languages 12: Functional programming
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CS 611: Lecture 9 More Lambda Calculus: Recursion, Scope, and Substitution September 17, 1999 Cornell University Computer Science Department Andrew Myers.
Tim Sheard Oregon Graduate Institute
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018.
An aggregation mechanism
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
Advanced Functional Programming
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Spring 2016.
Haskell Types, Classes, and Functions, Currying, and Polymorphism
CSE-321 Programming Languages Introduction to Functional Programming
Programming Languages and Compilers (CS 421) #3: Closures, evaluation of function applications, order of evaluation #4: Evaluation and Application.
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Spring 2019.
Presentation transcript:

Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture: Staged computation Difference between Haskell and ML Intro to MetaML Using staging to control evaluation order

Advanced Functional Programming Tim Sheard 2 Lecture 17 Differences in Types type variables and type application 'a Tree type constructors int, string, bool tuples (int * string * int) type variables and type application Tree a type constructors Int, String, Bool tuples (Int, String, Bool)

Advanced Functional Programming Tim Sheard 3 Lecture 17 Differences (* Data definitions *) datatype 'a Tree = Tip of 'a | Fork of ('a Tree)*('a Tree) 'a = type variable constructors are not capitalized -- data definitions data Tree a = Tip a | Fork (Tree a) (Tree a) comments Type constructors are post fix constructor functions are always uncurried (use tuples) note use of "of"

Advanced Functional Programming Tim Sheard 4 Lecture 17 difference 2 (* function definitions *) fun fact n = if n=0 then 1 else n * (fact (n-1)); fun depth (Tip a) = 0 | depth (Fork(x,y)) = 1 + max (depth x, depth y); -- function definitions fact n = if n==0 then 1 else n * (fact (n-1)) depth (Tip a) = 0 depth (Fork x y) = 1 + max (depth x) (depth y) note use of "fun" equality is double = use "bar" (|) to separate clauses primitives more likely to be curried in Haskell

Advanced Functional Programming Tim Sheard 5 Lecture 17 Data List a = [] | (:) a (list a) map f [] = [] map f (x:xs)=(f x):(map f xs) pi = \ x -> x + 1 Datatype ‘a list = [] | (op ::) of ‘a * (‘a list) fun map f [] = … | map f (x::xs) = val pi = fn x => x + 1 Differences between Haskell & ML

Advanced Functional Programming Tim Sheard 6 Lecture 17 Some Primitives - op +; val it = fn:int * int -> int - op *; val it = fn:int * int -> int - op -; val it = fn:int * int -> int - val it = fn:'a list * 'a list -> 'a list - length; val it = fn:'a list -> int - op ::; val it = fn:'a * 'a list -> 'a list - hd; val it = fn:'a list -> 'a - tl; val it = fn:'a list -> 'a list Main> :t (+) (+) :: Num a => a -> a -> a Main> :t (*) (*) :: Num a => a -> a -> a Main> :t (-) (-) :: Num a => a -> a -> a Main> :t (++) (++) :: [a] -> [a] -> [a] Main> :t length length :: [a] -> Int Main> :t (:) (:) :: a -> [a] -> [a] Main> :t head head :: [a] -> a Main> :t tail tail :: [a] -> [a]

Advanced Functional Programming Tim Sheard 7 Lecture 17 Differences 3 (* variable definition *) val tree1 = Fork(Fork(Tip 1,Tip 2), Tip 3); -- variable definition tree1 = Fork (Fork (Tip 1) (Tip 2)) (Tip 3) use val to declare variables

Advanced Functional Programming Tim Sheard 8 Lecture 17 functions fn x => x + 1 let fun f x = x + 1 in f 7 end has type in ML is : datatype T =... datatype ('a,'b) T =... = (in MetaML only) 'a ('b T) \ x -> x + 1 let f x = x + 1 in f 7 has type in Haskell is :: data T =... data T b a =...

Advanced Functional Programming Tim Sheard 9 Lecture 17 case expressions case x of [] => 5 | (x::xs) => len xs + m3 case x of [] -> 5 (x:xs) -> len xs + m3

Advanced Functional Programming Tim Sheard 10 Lecture 17 Differences 4 (* booleans *) - true; val it = true : bool - false; val it = false : bool (* mutual recursion *) fun even 0 = true | even n = odd (n-1) and odd 0 = false | odd n = even (n-1); -- booleans Main> :t True True :: Bool Main> :t False False :: Bool -- mutual recursion even 0 = True even n = odd (n-1) odd 0 = False odd n = even (n-1) No capitals use of "and" must separate mutually recursive functions all functions are implicitly mutually recursive

Advanced Functional Programming Tim Sheard 11 Lecture 17 Intro to MetaML

Advanced Functional Programming Tim Sheard 12 Lecture 17 Controlling Evaluation Order We want more than just the correct result! We want to control other resources such as time and space without resorting to tricks or unnatural programming styles. Mechanism - Control Evaluation Order

Advanced Functional Programming Tim Sheard 13 Lecture 17 Traditional Approaches Fixed evaluation order with language extensions Lazy - Outermost add strictness annotations Strict - Innermost add annotations like force and delay Encode laziness using lambda in a strict setting datatype 'a lazylist = lazyNil | lazyCons of 'a * (unit -> 'a lazylist); fun count n = lazyCons(n, fn () => count (n+1))

Advanced Functional Programming Tim Sheard 14 Lecture 17 Limitations None of these approaches allow computation under a lambda! This is sometimes just what is needed. For example: fun power n = (fn x => if n=0 then 1 else x * (power (n-1) x)) power 2;

Advanced Functional Programming Tim Sheard 15 Lecture 17 Example reduction (power 2) unfold the definition (fn x => if 2=0 then 1 else x * (power (2-1) x)) perform the if, under the lambda (fn x => x * (power (2-1) x)) unfold power again (fn x => x * ((fn x => if 1=0 then 1 else x * (power (1-1) x)) x)) use the beta rule to apply the explicit lambda to x

Advanced Functional Programming Tim Sheard 16 Lecture 17 Example (cont.) (fn x => x * (if 1=0 then 1 else x * (power (1-1) x))) perform the if (fn x => x * (x * (power (1-1) x))) unfold power again (fn x => x * (x * ((fn x => if 0=0 then 1 else x * (power (0-1) x))) x)) use the beta rule to apply the explicit lambda to x (fn x => x * (x * (if 0=0 then 1 else x * (power (0-1) x)))) perform the if (fn x => x * (x * 1))

Advanced Functional Programming Tim Sheard 17 Lecture 17 Solution - Use richer annotations Brackets: no reductions allowed in e delay computation if e:t then : (pronounced code of t) Escape: ~ e relax the no reduction rule of brackets above Escape may only occur inside Brackets splice code together to build larger code Run: run e remove outermost brackets force computations which have been delayed

Advanced Functional Programming Tim Sheard 18 Lecture 17 Calculus A calculus describes equivalences between program fragments. The rules of a calculus can be applied in any order. An implementation applies the rules in some fixed order. Traditional rules beta – (fn x => e) v  e[v/x] if – if true then x else y  x – if false then x else y  y delta –  7

Advanced Functional Programming Tim Sheard 19 Lecture 17 Rules for code Introduction rule for code 1st elimination rule for code (escape-bracket elim) … > ---> ~ must appear inside enclosing brackets e must be escape free must be at level 0 2nd elimination rule for code (run-bracket elim) run ---> e provided e has no escapes the whole expression is at level 0

Advanced Functional Programming Tim Sheard 20 Lecture 17 Power example revisited (* power : int -> -> *) fun power n = fn x => if n=0 then else (* ans : int > *) val ans = ~(power 2 ) >;

Advanced Functional Programming Tim Sheard 21 Lecture 17 ~ (power 2 ) > ~(if 2=0 then else * ~(power (2-1) ) >)> ~ * ~(power (2-1) ) >>) ~ ) >>) ~< z * ~(if 1=0 then else * ~(power (1-1) ) >) >>)

Advanced Functional Programming Tim Sheard 22 Lecture 17 ~ * ~(power (1-1) ) >>> ~ ) >>> ~ >>> ~ >> ~ > z * z * 1>

Advanced Functional Programming Tim Sheard 23 Lecture 17 MetaML: Meta-programming Meta-Programming: Programs that write programs What Infrastructure is possible in a language designed to help support the algorithmic construction of other programs? Advantages of meta-programs capture knowledge efficient solutions design ideas can be communicated and shared

Advanced Functional Programming Tim Sheard 24 Lecture 17 Types of meta-programs Static generators Generate code which is then “written to disk” and processed by normal compilers etc. Two kinds Homogeneous systems object language = meta-language Heterogeneous systems object-language different from meta-language Run-time generators Staged Programs Programs that generate other programs, and then execute the programs they generated MetaML is a staged programming language which does run-time code generation

Advanced Functional Programming Tim Sheard 25 Lecture 17 MetaML & the Mustang Project Theory Semantics of staged programs What does it mean to have a staged program? How can we tell if a staged program computes the same result as its unstaged counterpart? Calculus of programs - Rules for reasoning Staged type systems A static type system keeps bad programs from executing by throwing away bad programs by refusing to compile them. A staged program admits more bad things. E.g. using a variable before it is defined, or executing a program before its complete, for example. Staged languages need richer type systems to throw away these bad programs. Automatic staging partial evaluation

Advanced Functional Programming Tim Sheard 26 Lecture 17 MetaML & the Mustang Project Tools Staged Languages MetaML reflective: obj-lang = meta-lang = ML multi-stage Heterogeneous ( meta-lang=ML, obj-lang varies, 2 stage )

Advanced Functional Programming Tim Sheard 27 Lecture 17 Building pieces of code -| ; val it = : -| ; val it = : -| ; val it = : -| x + 5>; val it = a %+ 5)> : int> -| >; val it = )> : >

Advanced Functional Programming Tim Sheard 28 Lecture 17 Let’s try it ! Run MetaML

Advanced Functional Programming Tim Sheard 29 Lecture 17 Composing pieces of code -| val x = ; val x = : -| val y = ; val y = : -| fun pair x = ; val pair = Fn : ['b]. -> -| pair ; val it = :

Advanced Functional Programming Tim Sheard 30 Lecture 17 Executing constructed code -| val x = ; val x = : ['a]. -| run x; val it = 36 : int -| fun id x = x; val id = Fn : ['a].'a -> 'a -| val q = ) >; val q = : -| run q; val it = 6 : int

Advanced Functional Programming Tim Sheard 31 Lecture 17 Multi-stage code -| val z = >; val z = )> : > -| val f = run z; val f = Fn : int -> -| f 12; val it = : -| run it; val it = 13 : int

Advanced Functional Programming Tim Sheard 32 Lecture 17 The lift operator -| ; val it = : -| lift (4+1); val it = : -| val z = >; val z = )> : > -| run z; val it = Fn : int -> -| it 5; val it = : -| run it; val it = 6 : int

Advanced Functional Programming Tim Sheard 33 Lecture 17 Lift v.s. lexical capture Lift cannot be used on functions -| lift id; Error: The term: id Non Qualified type, not liftable: ? -> ? Lift makes code readable -| fun f x = ; val f = Fn : ['b^].'b -> -| f 3; val it = : Lexical capture is more efficient -| lift [1+3,4,8-4]; val it = :