# Tree Oriented Programming. Jeroen Fokker

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Tree Oriented Programming Jeroen Fokker

2 Tree oriented programming Many problems are like: Input text transform process unparse Output text

3 Tree oriented programming Many problems are like: Input text parse transform prettyprint unparse Output text internal tree representation

4 Tree oriented programming tools should facilitate: Defining trees Parsing Transforming Prettyprinting

5 Mainstream approach to tree oriented programming Defining trees Parsing Transforming Prettyprinting OO programming language preprocessor clever hacking library

6 Our approach to tree oriented programming Defining trees Parsing Transforming Prettyprinting functional language Haskell library preprocessor library

7 This morning s programme A crash course in Functional programming using Haskell Defining trees in Haskell The parsing library Transforming trees using the UU Attribute Grammar Compiler Prettyprinting Epilogue: Research opportunities

8 Language evolution: Imperative & Functional 50 years ago Now Haskell

9 Part I A crash course in Functional programming using Haskell

10 Function definition fac :: Int Int fac n = product [1..n] Haskell static int fac (int n) { int count, res; res = 1; for (count=1; count<=n; count++) res *= count; return res; }

11 Definition forms Function fac :: Int Int fac n = product [1..n] Constant pi :: Float pi = Operator (!^! ) :: Int Int Int n!^! k = fac n / (fac k * fac (n-k))

12 Case distinction with guards abs :: Int Int abs x x>=0 x<0 = x = -x guards

13 Case distinction with patterns day :: Int String day 1 = Monday day 2 = Tuesday day 3 = Wednesday day 4 = Thursday day 5 = Friday day 6 = Saturday day 7 = Sunday constant as formal parameter!

14 Iteration fac :: Int Int fac n n==0 = 1 n>0 = n * fac (n-1) without using standard function product recursion

15 List: a built-in data structure List: 0 or more values of the same type empty list constant put in front operator [ ] :

16 Shorthand notation for lists enumeration [ 1, 3, 8, 2, 5] > 1 : [2, 3, 4] [1, 2, 3, 4] range [ ] > 1 : [4..6] [1, 4, 5, 6]

17 Functions on lists sum :: [Int] Int sum [ ] = 0 sum (x:xs) = x + sum xs length :: [Int] Int length [ ] = 0 length (x:xs) = 1 + length xs patterns recursion

18 Standard library of functions on lists null ++ take > null [ ] True > [1,2] ++ [3,4,5] [1, 2, 3, 4, 5] > take 3 [2..10] [2, 3, 4] challenge: Define these functions, using pattern matching and recursion

19 Functions on lists null :: [a] Bool null [ ] = True null (x:xs) = False (++) :: [a] [a] [a] [ ] ++ ys = ys (x:xs) ++ ys = x : (xs++ys) take :: Int [a] [a] take 0 xs = [ ] take n [ ] = [ ] take n (x:xs) = x : take (n-1) xs

20 Polymorphic type Type involving type variables take :: Int [a] [a] Why did it take 10 years and 5 versions to put this in Java?

21 Functions as parameter Apply a function to all elements of a list map > map fac [1, 2, 3, 4, 5] [1, 2, 6, 24, 120] > map sqrt [1.0, 2.0, 3.0, 4.0] [1.0, , , 2.0] > map even [1.. 6] [False, True, False, True, False, True]

22 Challenge What is the type of map? map :: (a b) [a] [b] What is the definition of map? map f [ ] = map f (x:xs) = [ ] f x : map f xs

23 Another list function: filter Selects list elements that fulfill a given predicate > filter even [1.. 10] [2, 4, 6, 8, 10] filter :: (a Bool) [a] [a] filter p [ ] = [ ] filter p (x:xs) p x = x : filter p xs True = filter p xs

24 Higher order functions: repetitive pattern? Parameterize! product :: [Int] Int product [ ] = 1 product (x:xs) = x * product xs and :: [Bool] Bool and [ ] = True and (x:xs) = x && and xs sum :: [Int] Int sum [ ] = 0 sum (x:xs) = x + sum xs

25 Universal list traversal: foldr foldr :: (a b b) (a a a) b a [a] ba combining function start value foldr (#) e [ ] = foldr (#) e (x:xs)= e x # foldr (#) e xs

26 Partial parameterization foldr is a generalization of sum, product, and and... thus sum, product, and and are special cases of foldr product = foldr (*) 1 and = foldr (&&) True sum = foldr (+) 0 or = foldr ( ) False

27 Example: sorting (1/2) insert :: Ord a a [a] [a] insert e [ ] = [ e ] insert e (x:xs) e x = e : x : xs e x = x : insert e xs isort :: Ord a [a] [a] isort [ ] = [ ] isort (x:xs) = insert x (isort xs) isort = foldr insert [ ]

28 Example: sorting (2/2) qsort :: Ord a [a] [a] [a] qsort [ ] = [ ] qsort (x:xs) = qsort (filter (<x) xs) ++ [x] ++ qsort (filter ( x) xs) (Why don t they teach it like that in the algorithms course?)

29 Infinite lists repeat :: a [a] repeat x = x : repeat x > repeat 3 [3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3 replicate :: Int a [a] replicate n x = take n (repeat x) > concat (replicate 5 IPA ) IPA IPA IPA IPA IPA

30 Lazy evaluation Parameter evaluation is postponed until they are really needed Also for the (:) operator so only the part of the list that is needed is evaluated

31 Generic iteration iterate :: (a a) a [a] iterate f x = x : iterate f (f x) > iterate (+1) 3 [3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20

32 Convenient notations (borrowed from mathematics) Lambda abstraction \x x*x List comprehension [ x*y x [1..10], even x, y [1..x] ] for creating anonymous functions more intuitive than equivalent expression using map, filter & concat

33 Part II Defining trees in Haskell

34 Binary trees with internal labels How would you do this in Java/C++/C# etc?

35 The OO approach to trees class Tree { private Tree left, right; private int value; // constructor public Tree(Tree al, Tree ar, int av) { left = al; right=ar; value=av; } } // leafs are represented as null

36 The OO approach to trees: binary trees with external labels class Tree { // empty superclass } class Leaf extends Tree { int value } class Node extends Tree { Tree left,right }

37 Functional approach to trees I need a polymorphic type and constructor functions Tree a Leaf :: a Tree a Node :: Tree a Tree a Tree a Haskell notation: data Tree a = Leaf a Node (Tree a) (Tree a)

38 Example Data types needed in a compiler for a simple imperative language data Stat = Assign Name Expr Call Name [Expr] If Expr Stat While Expr Stat Block [Stat] type Name = String data Expr = Const Int Var Name Form Expr Op Expr data Op = Plus Min Mul Div

39 Functions on trees In analogy to functions on lists length :: [a] Int length [ ] = 0 length (x:xs) = 1 + length xs we can define functions on trees size :: Tree a Int size (Leaf v) = 1 size (Node lef rit) = size lef + size rit

40 Challenge: write tree functions elem tests element occurrence in tree elem :: Eq a a Tree a Bool elem x (Leaf y) = x==y elem x (Node lef rit) = elem x lef elem x rit front collects all values in a list front :: Tree a [a] front (Leaf y) = [ y ] front (Node lef rit) = front lef ++ front rit

41 A generic tree traversal In analogy to foldr on lists foldr :: (a b b) -- for (:) b -- for [ ] [a] b we can define foldt on trees foldt :: (a b) -- for Leaf (b b b) -- for Node Tree a b

42 Challenge: rewrite elem and front using foldt foldt :: (a b) -- for Leaf (b b b) -- for Node Tree a b elem x (Leaf y) = x==y elem x (Node lef rit) = elem x lef elem x rit elem x = foldt (==x) ( ) front (Leaf y) = [ y ] front (Node lef rit) = front lef ++ front rit front = foldt (\y [y]) :[] ) (++) (++)

43 Part III A Haskell Parsing library

44 Approaches to parsing Mainstream approach (imperative) Special notation for grammars Preprocessor translates grammar to C/Java/ -YACC (Yet Another Compiler Compiler) -ANTLR (ANother Tool for Language Recognition) Our approach (functional) Library of grammar-manipulating functions

45 ANTLR generates Java from grammar Expr : Term ( PLUS Term MINUS Term ) * ; Term : NUMBER OPEN Expr CLOSE ; public void expr () { term (); loop1: while (true) { switch(sym) { case PLUS: match(plus); term (); break; case MINUS: match(minus); term (); break; default: break loop1; } } } public void term() { switch(sym) { case INT: match(number); break; case LPAREN: match(open); expr (); match(close); break; default: throw new ParseError(); } }

46 ANTLR: adding semantics Expr returns [int x=0] { int y; } : x= Term ( PLUS y= Term { x += y; } MINUS y= Term { x = y; } ) * ; Term returns [int x=0] : n: NUMBER { x = str2int(n.gettext(); } OPEN x= Expr CLOSE ; Yacc notation: { \$\$ += \$1; }

47 A Haskell parsing library type Parser Building blocks symbol :: a satisfy :: (a Bool) Combinators epsilon :: Parser Parser Parser ( ) :: Parser Parser Parser ( ) :: Parser Parser Parser

48 A Haskell parsing library type Parser a b Building blocks symbol :: a satisfy :: (a Bool) Combinators start :: Parser a b [a] b epsilon :: Parser a () Parser a a Parser a a ( ) :: Parser a b Parser a b Parser a b ( ) :: Parser a b Parser a c Parser a (b,c) ( ) :: (b c) Parser a b Parser a c

49 Domainspecific Combinator Language vs. Library New notation and semantics Preprocessing phase What you got is all you get Familiar syntax, just new functions Link & go Extensible at will using existing function abstraction mechnism

50 Expression parser open = symbol ( close = symbol ) plus = symbol + minus = symbol data Tree = Leaf Int Node Tree Op Tree type Op = Char expr, term :: Parser Char Tree expr = Node term (plus minus) expr term term = Leaf number middle open expr close where middle (x,(y,z)) = y

51 Example of extensibility Shorthand open = symbol ( close = symbol ) Parameterized shorthand pack :: Parser a b Parser a b pack p = open p close middle New combinators many :: Parser a b Parser a [b]

52 The real type of ( ) How to combine b and c? ( ) :: Parser a b Parser a b Parser a b ( ) :: Parser a b Parser a c Parser a (b,c) ( ) :: (b c) Parser a b Parser a c ( ) ( ) :: Parser a b Parser a c (b c d) Parser a d :: Parser a (c d) Parser a c Parser a d pack p = open p close middle where middle x y z = y

53 Another parser example; design of a new combinator many :: Parser a b Parser a [b] many p = (\b bs b:bs) p many p (\e [ ]) epsilon many p = (:) p many p succeed [ ]

54 Challenge: parser combinator design EBNF * EBNF + Beyond EBNF many :: Parser a b Parser a [b] many1 :: Parser a b Parser a [b] sequence :: [ Parser a b ] Parser a [b] many1 p = sequence [ ] = sequence (p:ps) = (:) p many p sequence = foldr f (succeed []) where f p r = (:) p r succeed [ ] (:) p sequence ps

55 More parser combinators sequence :: [ Parser a b ] Parser a [b] choice :: [ Parser a b ] Parser a [b] listof :: Parser a b Parser a s Parser a [b] chain :: Parser a b Parser a (b b b) Parser a b choice = foldr ( ) fail listof p s = (:) p many ( ) separator (\s b b) s p

56 Example: Expressions with precedence data Expr = Con Int Var String Fun String [Expr] Expr :+: Expr Expr : : Expr Expr :*: Expr Expr :/: Expr Method call Parser should resolve precedences

57 Parser for Expressions (with precedence) expr = chain term ( (\o (:+:)) (symbol + ) (\o (: :)) (symbol ) ) term = chain fact ( (\o (:*:)) (symbol * ) (\o (:/:)) (symbol / ) ) fact = Con number pack expr Var name Fun name pack (listof expr (symbol, ) )

58 A programmers reflex: Generalize! expr = chain term ( (:+:) + (: :) ) term = chain fact ( (:*:) * (:/:) / ) gen ops next = chain next ( choice ops ) fact = basiccases pack expr

59 Expression parser (many precedence levels) expr = gen ops1 term1 term1= gen ops2 term2 term2= gen ops3 term3 term3= gen ops4 term4 term4= gen ops5 fact fact = basiccases pack expr expr = foldr gen fact [ops5,ops4,ops3,ops2,ops1] gen ops next = chain next ( choice ops )

60 Library implementation type Parser = String X type Parser b = String b polymorphic result type type Parser b = String (b, String) rest string type Parser a b = [a] (b, [a]) type Parser a b = [a] [ (b, [a]) ] polymorphic alfabet list of successes for ambiguity

61 Library implementation ( ) :: Parser a b Parser a b Parser a b (p q) xs = p xs ++ q xs ( ) :: Parser a (c d) Parser a c Parser a d (p q) xs = [ ( f c, zs ) (f,ys) p xs, (c,zs) q ys ] ( ) :: (b c) Parser a b Parser a c (f p) xs = [ ( f b, ys ) (b,ys) p xs ]

62 Part IV Techniques for Transforming trees

63 Data structure traversal In analogy to foldr on lists foldr :: (a b b) -- for (:) b -- for [ ] [a] b we can define foldt on binary trees foldt :: (a b) -- for Leaf (b b b) -- for Node Tree a b

64 Traversal of Expressions data Expr = Add Expr Expr Mul Expr Expr Con Int type ESem b = ( b b b, b b b, Int b ) folde :: (b b b) (b b b) (Int b) Expr b -- for Add -- for Mul -- for Con

65 Traversal of Expressions data Expr = Add Expr Expr Mul Expr Expr Con Int type ESem b = ( b b b, b b b, Int b ) folde :: ESem b Expr b folde (a,m,c) = f where f (Add e1 e2) = a (f e1) (f e2) f (Mul e1 e2) = m (f e1) (f e2) f (Con n) = c n

66 Using and defining Semantics data Expr = Add Expr Expr Mul Expr Expr Con Int type ESem b = ( b b b, b b b, Int b ) evalexpr :: Expr Int evalexpr = folde evalsem evalsem :: ESem Int evalsem = ( (+), (*), id )

67 Syntax and Semantics * 5 parseexpr Add (Con 3) (Mul (Con 4) (Con 5)) = start p where p = 23 evalexpr = folde s where s = (,,, )

68 Multiple Semantics * 5 parseexpr :: String Add (Con 3) (Mul (Con 4) (Con 5)) :: Expr evalexpr 23 = folde s where s = (,,, ) s::esem Int compileexpr Push 3 Push 4 Push 5 Apply (*) runcode :: Int :: Code Apply (+) = folde s where s = (,,, ) s::esem Code

69 A virtual machine What is machine code? type Code = [ Instr ] What is an instruction? data Instr = Push Int Apply (Int Int Int)

70 Compiler generates Code data Expr = Add Expr Expr Mul Expr Expr Con Int type ESem b = ( b b b, b b b, Int b ) evalexpr compexpr :: Expr Code Int evalexpr compexpr = folde compsem evalsem where evalsem compsem :: :: ESemInt Code evalsem compsem = = ( ((+) add, (*), mul, id, con ) ) mul :: Code Code Code mul c1 c2 = c1 ++ c2 ++ [Apply (*)] con n = [ Push n ]

71 Compiler correctness * 5 parseexpr Add (Con 3) (Mul (Con 4) (Con 5)) evalexpr compileexpr 23 runcode Push 3 Push 4 Push 5 Apply (*) Apply (+) runcode (compileexpr e) = evalexpr e

72 runcode: virtual machine specification run :: Code Stack Stack run [ ] stack = stack run (instr:rest) stack = run rest ( exec instr stack ) exec :: Instr Stack Stack exec (Push x) stack = x : stack exec (Apply f) (x:y:stack) = f x y : stack runcode :: Code Int runcode prog = run prog [ ] hd ( )

73 Extending the example: variables and local def s data Expr = Add Expr Expr Mul Expr Expr Con Int Var String Def String Expr Expr type ESem b = ( b b b, b b b, Int b ), String b, String b b b ) evalexpr :: Expr Int evalexpr = folde evalsem where evalsem :: ESem Int evalsem = ( add, mul, con ), var, def )

74 Any semantics for Expression add :: b b b add x y = mul :: b b b mul x y = con :: Int b con n = var :: String b var x = def :: String b b b def x d b =

75 Evaluation semantics for Expression add :: b b b add x y = x + y Int Int (Env Int) mul :: b b b mul x y = x * y Int Int (Env Int) con :: Int b con n = n var :: String b var x = Int Int def :: String Int b Int b b def x d b = Int

76 Evaluation semantics for Expression add :: b b b add x y = x + y Int Int (Env Int) mul :: b b b mul x y = x * y Int Int (Env Int) con :: Int b con n = n (Env Int) var :: String b var x = \e lookup e x (Env Int) def :: String Int b Int b b def x d b = (EnvInt

77 Evaluation semantics for Expression add ::(Env Int) b (Env Int) b b add x y = \e x e + y e Int Int (Env Int) mul :: (Env Int) b (Env Int) b b mul x y = \e x e * y e Int Int (Env Int) con :: Int b con n = \e n (Env Int) var :: String b var x = \e lookup e x (Env Int) def :: String (Env Int) b (Env Int) b b def x d b = \e b ((x,d e) : e ) (Env Int)

78 Extending the virtual machine What is machine code? type Code = [ Instr ] What is an instruction? data Instr = Push Int data Instr Push Int Apply (Int Int Int) Apply (Int Int Int) Load Adress Store Adress

79 Compilation semantics for Expression add ::(Env Code) b (Env Code) b Env b Code add x y = \e x e ++ y e ++ [Apply (+)] mul ::(Env Code) b (Env Code) b Env b Code mul x y = \e x e ++ y e ++ [Apply (*)] con :: Int b con n = \e [Push n] Env Code var :: String b var x = \e [Load (lookup e x)] Env Code where a = length e def :: String (Env Code) b (Env Code) b Env b Code def x d b = \e d e++ [Store a]++ b ((x,a) : e )

80 Language: syntax and semantics data Expr = Add Expr Expr Mul Expr Expr Con Int Var String Def String Expr Expr type ESem b = ( b b b, b b b, Int b, String b, String b b b ) compsem :: ESem (Env Code) compsem = (f1, f2, f3, f4, f5) where compile t = folde compsem t [ ]

81 Language: syntax and semantics data Expr = Add Expr Expr Mul Expr Expr Con Int Var String data DefStat String Expr Expr = Assign String Expr While Expr Stat If Expr Stat Stat Block [Stat] type ESem b c = ( ( b b b, b b b, Int b, String b,) String b b b, () String b c, b c c, b c c c, [ c ] c ) ) compsem :: ESem (Env Code) (Env Code) compsem = (f1, ((f1, f2, f3, f4, f4), f5) (f5, where f6, f7, f8)) compile t = folde compsem t [ ]

82 Real-size example data Module = data Class = data Method = data Stat = data Expr = data Decl = data Type = type ESem a b c d e f = ( (,, ), (,...), (,,,,, ), compsem :: ESem ( ) ( ) ( ) Attributes that are passed ( ) top-down ( ) ( ) ( ) compsem = ( dozens of functions ) Attributes that are generated bottom-up

83 Tree semantics generated by Attribute Grammar data Expr = Add Expr Expr Var String codesem = ( \ a b \ e a e ++ b e ++ [Apply (+)], \ x \ e [Load (lookup e x)], DATA Expr = Add a: Expr b: Expr Var x: String ATTR Expr inh e: Env syn c: Code Explicit names for fields and attributes SEM Expr Add this.code = a.code ++ b.code ++ [Apply (+)] a.e = this.e b.e = this.e Var this.code = [Load (lookup e x)] Attribute value equations instead of functions

84 UU-AGC Attribute Grammar Compiler Preprocessor to Haskell Takes: Attribute grammar Attribute value definitions Generates: datatype, fold function and Sem type Semantic function (many-tuple of functions) Automatically inserts trival def s a.e = this.e

85 UU-AGC Attribute Grammar Compiler Advantages: Very intuitive view on trees no need to handle 27-tuples of functions Still full Haskell power in attribute def s Attribute def s can be arranged modularly No need to write trivial attribute def s Disadvantages: Separate preprocessing phase

86 Part IV Pretty printing

87 Tree oriented programming Input text parse transform prettyprint Output text internal tree representation

88 Prettyprinting is just another tree transformation Example: transformation from Stat to String DATA Stat = Assign a: Expr b: Expr While e: Expr s: Stat Block body: [Stat] ATTR Expr Stat [Stat] syn code: String inh indent: Int SEM Stat Assign this.code = x.code ++ = ++ e.code ++ ; While this.code = while ( ++ e.code ++ ) ++ s.code Block this.code = { ++ body.code ++ } SEM Stat While s.indent = this.indent + 4 But how to handle newlines & indentation?

89 A combinator library for prettyprinting Type Building block Combinators type PPDoc text :: String PPDoc Observer (> <) :: PPDoc PPDoc PPDoc (> <) :: PPDoc PPDoc PPDoc indent :: Int PPDoc PPDoc render :: Int PPDoc String

90

91 Epilogue Research opportunities

92 Research opportunities (1/4) Parsing library: API-compatible to naïve library, but With error-recovery etc. Optimized Implemented using the Attribute Grammar way of thinking

93 Research opportunities (2/4) UU - Attribute Grammar Compiler More automatical insertions Pass analysis optimisation

94 Research opportunities (3/4) A real large compiler (for Haskell) 6 intermediate datatypes 5 transformations + many more Learn about software engineering aspects of our methodology

95 Reasearch opportunities (4/4) Generate as much as possible with preprocessors Attribute Grammar Compiler Shuffle extract multiple views & docs from the same source Ruler generate proof rules checked & executable.rul.cag.ag.hs.o.exe

INTRODUCTION TO HASKELL PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2018 Dalhousie University 1/81 HASKELL: A PURELY FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be

### Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

### These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without previous written authorization. 1 2 The simplest way to create

### CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

### Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

### CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

### Thoughts on Assignment 4 Haskell: Flow of Control

Thoughts on Assignment 4 Haskell: Flow of Control CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 27, 2017 Glenn G. Chappell Department of Computer

### Shell CSCE 314 TAMU. Functions continued

1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

### Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

### PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

### CSCE 314 Programming Languages. Functional Parsers

CSCE 314 Programming Languages Functional Parsers Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a text (set of tokens) and determines its syntactic structure. String or [Token]

### Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### Functional abstraction

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

CSci 450: Org. of Programming Languages Overloading and Type Classes H. Conrad Cunningham 27 October 2017 (after class) Contents 9 Overloading and Type Classes 1 9.1 Chapter Introduction.........................

### Programming Language Concepts, CS2104 Lecture 7

Reminder of Last Lecture Programming Language Concepts, CS2104 Lecture 7 Tupled Recursion Exceptions Types, ADT, Haskell, Components 5th Oct 2007 CS2104, Lecture 7 1 Overview 5th Oct 2007 CS2104, Lecture

### COP 3402 Systems Software Syntax Analysis (Parser)

COP 3402 Systems Software Syntax Analysis (Parser) Syntax Analysis 1 Outline 1. Definition of Parsing 2. Context Free Grammars 3. Ambiguous/Unambiguous Grammars Syntax Analysis 2 Lexical and Syntax Analysis

### Programming with Math and Logic

.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

### Monad Background (3A) Young Won Lim 11/18/17

Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

### Lecture 2: List algorithms using recursion and list comprehensions

Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns

### CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists

### INFOB3TC Solutions for the Exam

Department of Information and Computing Sciences Utrecht University INFOB3TC Solutions for the Exam Johan Jeuring Monday, 13 December 2010, 10:30 13:00 lease keep in mind that often, there are many possible

Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

### COMP 181. Prelude. Prelude. Summary of parsing. A Hierarchy of Grammar Classes. More power? Syntax-directed translation. Analysis

Prelude COMP 8 October, 9 What is triskaidekaphobia? Fear of the number s? No aisle in airplanes, no th floor in buildings Fear of Friday the th? Paraskevidedekatriaphobia or friggatriskaidekaphobia Why

### Programming Languages Fall 2013

Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

### CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

CSE 130: Programming Languages Polymorphism Ranjit Jhala UC San Diego Q: What is the value of res? let f g = let x = 0 in g 2 let x = 100 let h y = x + y let res = f h (a) 0 (b) 2 (c) 100 (d) 102 (e) 12

### A tour of the Haskell Prelude

A tour of the Haskell Prelude Bernie Pope 2001 1 Haskell The Haskell language was conceived during a meeting held at the 1987 Functional Programming and Computer Architecture conference (FPCA 87). At the

CIS552: Advanced Programming Handout 8 What is a Parser? A parser is a program that analyzes a piece of text to deine its structure (and, typically, returns a tree representing this structure). The World

### FUNCTIONAL AND LOGIC PROGRAMS

FUNCTIONAL AND LOGIC PROGRAMS Contents Language Specific Compilation Context Handling Identification Scope Overloading Imported Scope Type Checking Type table Type equivalence Coercions Casts and conversions

### CS664 Compiler Theory and Design LIU 1 of 16 ANTLR. Christopher League* 17 February Figure 1: ANTLR plugin installer

CS664 Compiler Theory and Design LIU 1 of 16 ANTLR Christopher League* 17 February 2016 ANTLR is a parser generator. There are other similar tools, such as yacc, flex, bison, etc. We ll be using ANTLR

### Haskell Making Our Own Types and Typeclasses

Haskell Making Our Own Types and Typeclasses http://igm.univ-mlv.fr/~vialette/?section=teaching Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée January 13, 2015 Making Our Own Types and Typeclasses

### CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,

### Principles of Programming Languages

Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Introduc;on to Hakell Lesson 27! 1 The origins: ML programming

### To figure this out we need a more precise understanding of how ML works

Announcements: What are the following numbers: 52/37/19/6 (2:30,3:35,11:15,7:30) PS2 due Thursday 9/22 11:59PM Quiz #1 back in section Monday Quiz #2 at start of class on Thursday 9/22 o HOP s, and lots

### Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)

Chapter 3: Describing Syntax and Semantics Introduction Formal methods of describing syntax (BNF) We can analyze syntax of a computer program on two levels: 1. Lexical level 2. Syntactic level Lexical

### University of Utrecht. 1992; Fokker, 1995), the use of monads to structure functional programs (Wadler,

J. Functional Programming 1 (1): 1{000, January 1993 c 1993 Cambridge University Press 1 F U N C T I O N A L P E A R L S Monadic Parsing in Haskell Graham Hutton University of Nottingham Erik Meijer University

### Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

### Compilers. Compiler Construction Tutorial The Front-end

Compilers Compiler Construction Tutorial The Front-end Salahaddin University College of Engineering Software Engineering Department 2011-2012 Amanj Sherwany http://www.amanj.me/wiki/doku.php?id=teaching:su:compilers

### List Functions, and Higher-Order Functions

List Functions, and Higher-Order Functions Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ List Functions, and Higher-Order

### Chapter 3 (part 3) Describing Syntax and Semantics

Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings

### Programming Languages

CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f -> fun x -> not (f x); # let

### Week 5 Tutorial Structural Induction

Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

### According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

Lecture 7: Haskell CSC 131 Fall, 2014 Kim Bruce According to Larry Wall (designer of PERL): a language by geniuses for geniuses He s wrong at least about the latter part though you might agree when we

### Recap: ML s Holy Trinity

Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set

### CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

Recall Architecture of Compilers, Interpreters CMSC 330: Organization of Programming Languages Source Scanner Parser Static Analyzer Operational Semantics Intermediate Representation Front End Back End

### Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

### Informatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 7 Map, filter, fold Don Sannella University of Edinburgh Part I Map Squares *Main> squares [1,-2,3] [1,4,9] squares :: [Int] -> [Int] squares xs [ x*x x

### CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

### Context-Free Grammar. Concepts Introduced in Chapter 2. Parse Trees. Example Grammar and Derivation

Concepts Introduced in Chapter 2 A more detailed overview of the compilation process. Parsing Scanning Semantic Analysis Syntax-Directed Translation Intermediate Code Generation Context-Free Grammar A

### Writing Evaluators MIF08. Laure Gonnord

Writing Evaluators MIF08 Laure Gonnord Laure.Gonnord@univ-lyon1.fr Evaluators, what for? Outline 1 Evaluators, what for? 2 Implementation Laure Gonnord (Lyon1/FST) Writing Evaluators 2 / 21 Evaluators,

### Programming in Haskell Aug-Nov 2015

Programming in Haskell Aug-Nov 2015 LECTURE 14 OCTOBER 1, 2015 S P SURESH CHENNAI MATHEMATICAL INSTITUTE Enumerated data types The data keyword is used to define new types data Bool = False True data Day

### Shell CSCE 314 TAMU. Higher Order Functions

1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

### Syntax Analysis/Parsing. Context-free grammars (CFG s) Context-free grammars vs. Regular Expressions. BNF description of PL/0 syntax

Susan Eggers 1 CSE 401 Syntax Analysis/Parsing Context-free grammars (CFG s) Purpose: determine if tokens have the right form for the language (right syntactic structure) stream of tokens abstract syntax

### Programming Languages

CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

### CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

CSE 130 Programming Languages Lecture 3: Datatypes Ranjit Jhala UC San Diego News? PA #2 (coming tonight) Ocaml-top issues? Pleas post questions to Piazza Recap: ML s Holy Trinity Expressions (Syntax)

### Principles of Programming Languages

Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

### Monads seen so far: IO vs Gen

Monads David Sands Monads seen so far: IO vs Gen IO A Gen A Instructions to build a value of type A by interacting with the operating system Instructions to create a random value of type A Run by the ghc

### CSCE 314 Programming Languages. Monadic Parsing

CSCE 314 Programming Languages Monadic Parsing Dr. Hyunyoung Lee 1 What is a Parser? A parser is a program that takes a string of characters (or a set of tokens) as input and determines its syntactic structure.

### Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

CSE 130 Programming Languages Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Datatypes Compile-time Static Types Ranjit Jhala UC San Diego 1. Programmer enters expression

### EDAN65: Compilers, Lecture 06 A LR parsing. Görel Hedin Revised:

EDAN65: Compilers, Lecture 06 A LR parsing Görel Hedin Revised: 2017-09-11 This lecture Regular expressions Context-free grammar Attribute grammar Lexical analyzer (scanner) Syntactic analyzer (parser)

Functional Programming Language Haskell Mohammed Aslam CIS 24 Prof. Kopec Presentation: 03 Date: 05/05/2003 Haskell is a general purpose, purely functional programming language named after the logician

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Context Free Grammars and Parsing 1 Recall: Architecture of Compilers, Interpreters Source Parser Static Analyzer Intermediate Representation Front End Back

### Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f

### CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages Context Free Grammars 1 Architecture of Compilers, Interpreters Source Analyzer Optimizer Code Generator Abstract Syntax Tree Front End Back End Compiler

### Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,

### Functional Programming - 2. Higher Order Functions

Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

### Begin at the beginning

Begin at the beginning Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set of

### CS 381: Programming Language Fundamentals

CS 381: Programming Language Fundamentals Summer 2017 Semantics July 12, 2017 Outline What is semantics? Semantics of naming 2 Why do we need semantics? Understand what program constructs do Judge the

### Functional Programming TDA 452, DIT 142

Chalmers Göteborgs Universitet 2018-01-11 Examiner: Thomas Hallgren, D&IT, Answering questions at approx 15.00 (or by phone) Functional Programming TDA 452, DIT 142 2018-01-11 14.00 18.00 Samhällsbyggnad

### MIT Specifying Languages with Regular Expressions and Context-Free Grammars

MIT 6.035 Specifying Languages with Regular essions and Context-Free Grammars Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology Language Definition Problem How to precisely

### TYPES, VALUES AND DECLARATIONS

COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1 Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier

### GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

GADTs Advanced functional programming - Lecture 7 Wouter Swierstra and Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree

Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

### CS 209 Functional Programming

CS 209 Functional Programming Lecture 03 - Intro to Monads Dr. Greg Lavender Department of Computer Science Stanford University "The most important thing in a programming language is the name. A language

### CSE 307: Principles of Programming Languages

1 / 63 CSE 307: Principles of Programming Languages Syntax R. Sekar Topics 1. Introduction 2. Basics 3. Functions 4. Data Structures 5. Overview 6. OCAML Performance 2 / 63 3 / 63 Section 1 Introduction

### News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A

### Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

### CSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point

Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form

### CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages Syntax R. Sekar 1 / 63 Topics 1. Introduction 2. Basics 3. Functions 4. Data Structures 5. Overview 6. OCAML Performance 2 / 63 Section 1 Introduction 3 / 63

### CS 457/557: Functional Languages

CS 457/557: Functional Languages From Trees to Type Classes Mark P Jones Portland State University 1 Trees:! " There are many kinds of tree data structure.! " For example: data BinTree a = Leaf a BinTree

### Topic 3: Syntax Analysis I

Topic 3: Syntax Analysis I Compiler Design Prof. Hanjun Kim CoreLab (Compiler Research Lab) POSTECH 1 Back-End Front-End The Front End Source Program Lexical Analysis Syntax Analysis Semantic Analysis

### Denotational Semantics. Domain Theory

Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

### Option Values, Arrays, Sequences, and Lazy Evaluation

Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,

### CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No

### HIGHER-ORDER FUNCTIONS

5 HIGHER-ORDER FUNCTIONS Haskell functions can take functions as parameters and return functions as return values. A function that does either of these things is called a higher-order function. Higher-order

### CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

### Better Extensibility through Modular Syntax. Robert Grimm New York University

Better Extensibility through Modular Syntax Robert Grimm New York University Syntax Matters More complex syntactic specifications Extensions to existing programming languages Transactions, event-based

### CSCI-GA Final Exam

CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

### CS 11 Ocaml track: lecture 6

CS 11 Ocaml track: lecture 6 n Today: n Writing a computer language n Parser generators n lexers (ocamllex) n parsers (ocamlyacc) n Abstract syntax trees Problem (1) n We want to implement a computer language

### Continuation Passing Style. Continuation Passing Style

161 162 Agenda functional programming recap problem: regular expression matcher continuation passing style (CPS) movie regular expression matcher based on CPS correctness proof, verification change of

### Part I: Multiple Choice Questions (40 points)

Preparatory Course Grammars and Parsing Friday, November 11, 2005 (9:00-12:00 This exam consists of 10 multiple-choice questions (Part I and 3 open questions (Part II. The maximum number of points for

### Consider the following EBNF definition of a small language:

xercise 1: Consider the following BNF definition of a small language: program ::= + decl ::= vardecl ::= "var" ":" "=" ";" procdecl ::= "procedure"

### IR Optimization. May 15th, Tuesday, May 14, 13

IR Optimization May 15th, 2013 Tuesday, May 14, 13 But before we talk about IR optimization... Wrapping up IR generation Tuesday, May 14, 13 Three-Address Code Or TAC The IR that you will be using for

### Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh

Informatics 1 Functional Programming Lecture 12 Data Abstraction Don Sannella University of Edinburgh Part I Sets as lists without abstraction We will look again at our four ways of implementing sets.

### A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data