Concepts of programming languages
|
|
- Cory Hines
- 6 years ago
- Views:
Transcription
1 Concepts of programming languages Lecture 9 Wouter Swierstra 1
2 Talks advice Focus on what makes your language different or interesting. Giving small examples can really help give a feel for a new language. Go slow. Take the time to talk us through these examples. Remember it s the first time for most people in the audience to read code in this language. Don t try to cover too much ground: instead try to convey a handful of key points. 2
3 Last time Racket is a strict, dynamically typed functional language of the Lisp/Sheme family. The syntax and language features are fairly minimalisticy. But this makes it very easy to manipulate code as data. Macros let us define new programming constructs in terms of existing ones. By customizing the parser even further, we can embed other languages in Racket or define our own Racket-dialects. 3
4 Metaprogramming in Racket > (eval '(+ (* 1 2) 3)) 6 Quoting can turn any piece of code into data Using eval we can interpret a quoted expression and compute the associated value. 4
5 Today How do other (typed) languages support this style of metaprogramming? Case studies: when do people use reflection? Embedding DSLs using quasiquotation. 5
6 Two separate aspects We can tease apart two separate issues: How to inspect a piece of code? (Reflection or quotation) How to generate or run new code? (Metaprogramming) These ideas pop up over and over again in different languages. Many dynamically typed languages borrow ideas from the Lisp-family of languages. 6
7 Javascript: object reflection Objects in Javascript are little more than a map from its attributes and methods to the associated values. Given any object o, we can iterate over all its methods and attributes: for (var key in o) { console.log(key + " -> " + o[key]); } This lets us reflect and inspect the object structure. 7
8 Javascript: eval As we saw previously, we can evaluate any string corresponding to a program fragment: var x = 3; var y = 7; var z = eval("x * y") Note that eval is incredibly unsafe! Question: In what ways can this fail? 8
9 Javascript: eval As we saw previously, we can evaluate any string corresponding to a program fragment: var x = 3; var y = 7; var z = eval("x * y") Note that eval is incredibly unsafe! Question: In what ways can this fail? Illegal syntax: eval("2#2k-sa[2da") Reference to unbound variables eval("3 * z") Type errors: eval("1.touppercase()") Dynamic execution errors: eval("1/0") 8
10 C# reflection In C# there are limited ways in which we can reflect the type of a piece of data: int i = 42; System.Type type = i.gettype(); System.Console.WriteLine(type); This prints System.Int32. Similarly to Javascript, we can request the attributes and functions of a class and iterate over these. But what about generating new code? 9
11 Metaprogramming in C# There is no way to generate new C# ASTs But you can emit machine code instructions dynamically. All.NET languages, including C#, F#, and Visual Basic, are compiled to the Common Intermediate Language (CIL). This is stack-based assembly language that is either executed natively or run on a virtual machine. 10
12 Example: Emitting CIL instructions A simple call to WriteLine: Console.WriteLine("Hello World"); Becomes 11
13 private void EmitCode(MethodBuilder builder, string text) { ILGenerator generator = builder.getilgenerator(); generator.emit(opcodes.ldstr, text); MethodInfo methodinfo = typeof(system.console).getmethod( "WriteLine", BindingFlags.Public BindingFlags.Static, null, new Type[]{typeof(string)}, null); } generator.emit(opcodes.call, methodinfo); generator.emit(opcodes.ret); 12 With another 100 lines of boilerplate
14 Metaprogramming in C# We can generate new bytecode and inspect existing classes this doesn t scale very well to larger examples; emitting CIL codes is essentially untyped and unsafe. But it is a good example of a different style of metaprogramming where the generating language (C#) and generated language (CIL) are different. 13
15 Metaprogramming in other languages More advanced systems such as Scala s Lightweight modular staging will be presented after the Christmas break. What about metaprogramming in a strongly typed language such as Haskell? 14
16 Template Haskell There is a language extension, Template Haskell, that provides metaprogramming support for Haskell. This defines support for quotating code into data and splicing generated code back into your program. 15
17 Template Haskell import Language.Haskell.TH three :: Int three = threeq :: ExpQ threeq = [ ] Rather than Racket s quote function, we can enclose expressions in quotation brackets [... ]. This turns code into a quoted expression, ExprQ. 16
18 Unquoting > three 3 > $threeq 3 We can splice an expression e back into our program by writing $e (note the lack of space between $ and e) This runs the associated metaprogram and replaces the occurrence $e with its result. 17
19 Inspecting code What happens when we quote an expression? 18
20 Inspecting code What happens when we quote an expression? > runq [ ] InfixE (Just (LitE (IntegerL 1))) (VarE GHC.Num.+) (Just (LitE (IntegerL 2))) Template Haskell defines a data type Exp corresponding to Haskell expressions. The type ExpQ is a synonym for Q Exp a value of type Exp in the quotation monad Q. The runq function returns the quoted expression associated with ExpQ. 18
21 The Exp data type data Exp = VarE Name -- variables ConE Name -- constructors LitE Lit -- literals such as 5 or 'c' AppE Exp Exp -- application ParensE Exp -- parentheses LamE [Pat] Exp -- lambdas TupE [Exp] -- tuples LetE [Dec] Exp -- let CondE Exp Exp Exp -- if-then-else... Not to mention unboxed tuples, record updates, record construction, lists, list comprehensions, 19
22 Template Haskell: programming with expressions incr : Int -> Int incr x = x + 1 incre : Exp -> Exp incre e = AppE (VarE 'incr) e) The first incr function increments a number; The second takes a quoted expression as argument and builds a new expression by passing its argument to incr. We can quote variable names with the prefix quotation mark 'incr 20
23 Template Haskell: programming with expressions -- Let x = [ ] x : Exp x = InfixE (Just (LitE (IntegerL 1)))... y : Int y = $(incre x) Question: What is the result of evaulating y? 21
24 Template Haskell: programming with expressions -- Let x = [ ] x : Exp x = InfixE (Just (LitE (IntegerL 1)))... y : Int y = $(incre x) Question: What is the result of evaulating y? But this might go wrong 21
25 Typing Template Haskell What happens when we create ill-typed expressions? -- Let x = [ "Hello world" ] x : Exp x = LitE (StringL "Hello World") y : Int y = $(incre x) Question: What is the result of this program? 22
26 Typing Template Haskell What happens when we create ill-typed expressions? -- Let x = [ "Hello world" ] x : Exp x = LitE (StringL "Hello World") y : Int y = $(incre x) Question: What is the result of this program? We get a type error: No instance for (Num [Char]) arising from a use of incr In the expression: incr "Hello World"... 22
27 Typing Template Haskell Template Haskell is a staged programming language. The compiler starts by type checking the program even the program fragments building up expressions: x : Exp x = LitE (StringL "Hello World") But it ignores any splices: y : Int y = $(incre x) It does not yet know if y is type correct or not 23
28 Typing Template Haskell Once the basic types are correct, the compiler can safely compute new code (such as that arising from the call incre x). So during type checking the compiler needs to perform evaluation. It can then replace splices, such as $(incre x) with result of evaluation. 24
29 Typing Template Haskell But even then, we don t know if the generated code is type correct. At this point, the splice $(incre x) will be replaced by incr "Hello World". The compiler type checks the generated code, which may raise an error. Question: Is two passes enough? 25
30 Typing Template Haskell But even then, we don t know if the generated code is type correct. At this point, the splice $(incre x) will be replaced by incr "Hello World". The compiler type checks the generated code, which may raise an error. Question: Is two passes enough? Not in general - the generated code may contain new program splices. 25
31 Type safety Question: So is Template Haskell statically typed? 26
32 Type safety Question: So is Template Haskell statically typed? Yes: all generated code is type checked. No: metaprograms are essentially untyped. 26
33 Type safe metaprograms Template Haskell also provides a data type for typed expressions : newtype TExp a = TExp { untype :: Exp } The type variable is not used, but tags an expression with the type we expect it to have. This is sometimes known as a phantom type. This can be used to give us some more type safety: appe :: TExp (a -> b) -> TExp a -> TExp b appe (TExp f) (TExp x) = TExp (AppE f x) Question: Where does this break? 27
34 Limited safety There are lots of ways to break this. Referring to variables is one way: bogus :: TExp String bogus = TExp (VarE 'incr) But more generally, there are plenty of situations where we cannot easily figure out the types of the metaprogram that we generate. 28
35 Beyond expressions The Exp data type is used to reflect expressions. But Template Haskell also provides data types describing: Patterns Function definitions Data type declarations Class declarations Instance definitions Compiler pragmas Together with the technology to reflect code into such data types. 29
36 Beyond expressions As a result, we can generate arbitrary code fragments using Template Haskell: new type signatures; new data type declarations; new classes or class instances; Any pattern in our code that we can describe programmatically can be automated throught Template Haskell. 30
37 Template Haskell: examples There are ways in which people use of Template Haskell: Generalizing a certain pattern of functions: zip :: [a] -> [b] -> [(a,b)] zip3 :: [a] -> [b] -> [c] -> [(a,b,c)] zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]... Automating boilerplate code (lenses); Including system information (git-embed). Interfacing safely to an external data source, such as a database, requires computing new marshalling/unmarshalling functions (printf). 31
38 Example: git-embed Suppose that we want to include version information about our program. > mytool --version Built from the branch 'master' with hash 410d5264a We could do this in numerous ways: maintain a version variable in our code manually; have a shell script that generates this information whenever we release code; splice this information into our code using Template Haskell. 32
39 Example: git-embed There is a library using Template Haskell, git-embed, that provides precisely this functionality. Using it is easy enough: import Git.Embed gitrev :: String gitrev = $(embedgitshortrevision) gitbranch :: String gitbranch = $(embedgitbranch) How is it implemented? 33
40 Example: git-embed ideas Functions such as embedgitbranch need to compute a string, corresponding to the current git branch. To do so: 1. We perform a bit of I/O, running git branch with suitable arguments; 2. The result of this command contains the information that we are after. 3. Quoting this result back into a string literal, yields the desired value. Note: we can run IO computations while metaprogramming 34
41 Example: git-embed implementation embedgitbranch : ExpQ embedgitbranch = embedgit ["rev-parse", "--abbrev-ref", "HEAD"] embedgit :: [String] -> ExpQ embedgit args = do addrefdependentfiles gitout <- runio (readprocess "git" args "") return $ LitE (StringL gitout) The addrefdependentfiles adds the files from the.git directory as dependencies. If these files change, the module will be recompiled. 35
42 Quotation and I/O This example illustrates that we can run I/O operations during quotation. Question: Why should this be allowed? And what are the drawbacks? 36
43 Quotation and I/O This example illustrates that we can run I/O operations during quotation. Question: Why should this be allowed? And what are the drawbacks? Makes it possible to read data from a file, network, database, etc. and use this information to generate new code or write new data to a file. The compiling code may have side effects! You can write a Haskell program that formats your hard-drive when compiled. 36
44 Example: printf If you ve ever done any debugging with C, you will have encountered printf: char* username; x =... ; y =... ; printf("x,y, and user are now:") printf("x=%d,y=%d,user=%s",x,y,username); The printf function takes a variable number of arguments: depending on the format string, it expects a different number of integers and strings. What is its type? 37
45 Example: printf using Template Haskell We ll sketch how to implement a printf function in Haskell: > $(printf "x=%d,s=%s") 6 "Hello" "x=6,s=hello" The key idea is to use the argument string to compute a function taking suitable arguments. Splicing $(printf "x=%d,s=%s") will compute the term: \n0 -> \s1 -> "x=" ++ shown0 ++ ",s=" ++ s1 38
46 Example: printf printf :: String -> ExpQ printf s = gen (parse s) data Format = D S L String parse :: String -> [Format] gen :: [Format] -> ExpQ 39 The printf function maps a string to an expression; The parse function reads in the string and splits it into a series of format instructions it doesn t use any Template Haskell and I won t cover it further. Depending on these instructions, the gen command will compute a different expression.
47 Example: printf Let s try to figure out how the gen function works in several different steps. data Format = D S L String gen :: [Format] -> ExpQ gen [] = LitE (StringL "") If the list of formatting directives is empty, we compute the empty string that was easy enough. 40
48 Example: printf Now suppose we only ever have to worry about handling a single formatting directive: data Format = D S L String gen :: [Format] -> ExpQ gen [D] = [ \n -> show n ] gen [S] = [ \s -> s ] gen [L str] = LitE (StringL str) Each individual case generates the code that we would write by hand otherwise. 41
49 Example: printf printf :: String -> Exp printf s = gen (parse s) [ "" ] gen :: [Format] -> Exp -> Exp gen [] e = e gen (D:fmts) e = [ \n-> $(gen fmts [ $e ++ show n ]) ] gen (S:fmts) e = [ \s-> $(gen fmts [ $e ++ s ]) ] gen (L s:fmts) e = gen fmts [ $e ++ $(LitE (StringL s)) ] The gen function is defined using an accumulating parameter. Initially, this is just the empty string. 42
50 Example: printf printf :: String -> Exp printf s = gen (parse s) [ "" ] gen :: [Format] -> Exp -> Exp gen [] e = e gen (D:fmts) e = [ \n-> $(gen fmts [ $e ++ show n ]) ] gen (S:fmts) e = [ \s-> $(gen fmts [ $e ++ s ]) ] gen (L s:fmts) e = gen fmts [ $e ++ $(LitE (StringL s)) ] As we encounter more formatting directives, we add an additional lambda if necessary and perform a recursive call. Note the subtle interplay between splicing and quoting. 43
51 Example: printf This example shows how to compute new expressions from existing data. This same pattern pops up whenever we want to interface with an external data source, such as database: Request information about the table layout; Parse the result and generate corresponding types; Generate functions to access the data. 44
52 Record management Records in Haskell provide a convenient way to organize structured data. data Person = {name :: String, address :: Address} data Address = {street :: String, city :: String} In practice, these records can be huge. 45
53 Nested records We can use the record fields to project out the desired information. If we need to access nested fields, we can define our own projection functions: personcity :: Person -> City personcity = city. address Record projections compose nicely. What about record updates? 46
54 Nested records But setting nested fields is pretty painful: setcity :: City -> Address -> Address setcity newcity a = a {city = newcity} setaddress :: Address -> Person -> Person setaddress newaddress p = p {address = newaddress} setpersoncity :: City -> Person -> Person setpersoncity newcity p = setaddress (setcity newcity (address p)) p This is already quite some boilerplate code code that is not interesting and follows a fixed pattern. 47
55 Example: lenses To automate this, we can package the getter and setter functions in a single data type, sometimes reffered to as a lens: data (:->) a b = Lens { get : a -> b, set : b -> a -> a } Such lenses compose nicely: compose :: (b :-> c) -> (a :-> b) -> (a :-> c) 48
56 Example: lenses In our example, suppose we are given lenses for every record field: city :: (Address :-> String) address :: (Person :-> Address) We can compose these lenses by hand, to assemble the pieces of data that we re interested in: personcity :: Person :-> City personcity = compose city address updatecity :: City -> Person -> Person updatecity newcity = set personcity newcity 49
57 Example: lenses Lenses make the manipulation nested records manageable. But who writes the lenses? This is not hard to do by hand: city :: Address :-> City city = Lens { get = \a -> city a, set = \nc a -> a {city = nc} } But could clearly use some automation. 50
58 Example: fclabels The fclabels package defines the type of lenses together with a Template Haskell module that generates the lenses associated with any given record: data Person = Person { _name :: String, _address :: Address} data Address = Address { _city :: City, _street :: String} mklabel ''Address mklabel ''Person 51 The double quotes ''Address quotes type Adress the distinction can be necessary.
59 Example: fclabels What does the Template Haskell code do? 1. Given a quoted record name, looks up the associated record declaration; 2. For each field, generate a suitable lens by: 2.1 looking up the type of the field; 2.2 generating the type signature of the required lens; 2.3 generating a name for the lens, based on the field name; 2.4 generating an expression corresponding to the lens definition; 3. Splicing all these declarations back into the file. About 700 loc but handles different flavours of lenses and generalizations. 52
60 Example: fclabels This example sketches how you might want to use Template Haskell to generate code. There is a clear pattern showing how to define a lens for any given record But we need metaprogramming technology to automate this. 53
61 Quasiquotation As a last example, I want to briefly mention quasiquotation. We ve seen how to embed domain specific languages in Haskell using deep/shallow embeddings. When we do so, we are constrained by Haskell s syntax and static semantics. Racket shows how to use macros to write custom language dialects. Haskell s quasiquotation framework borrows these ideas. 54
62 Quasiquotation: example Suppose I m writing a Haskell library for manipulating and generating C code. But working with C ASTs directly is pretty painful: add n = Func (DeclSpec [ ] [ ] (Tint Nothing)) (Id "add") DeclRoot (Args [Arg (Just (Id "x"))... What I d like to do is embed (a fragment of) C in my Haskell library. 55
63 Using quasiquotation The quasiquoter allows me to do just that: add n = [cfun int add (int x ) { return x + $int : n$; } ] The cfun quasiquoter tells me how to turn a string into a suitable Exp. 56
64 Defining quasiquoters A quasiquoter is nothing more than a series of parsers for expressions, patterns, types and declarations: data QuasiQuoter = QuasiQuoter { quoteexp :: String -> Q Exp, quotepat :: String -> Q Pat, quotetype :: String -> Q Type, quotedec :: String -> Q [Dec] } Whenever the Haskell parser encounters a quasiquotation [ myqq... ] it will run the parser associated with the quasiquoter myqq to generate the quoted expression/pattern/type/declaration. 57
65 Multiline strings As a simple example, suppose we want to have multi-line string literals. We can define a quasiquoter: ml :: QuasiQuoter ml = QuasiQuoter { quoteexp = (\a -> LitE (StringL a)),... } And call it as follows: example : String example = [ml hello beautiful world ] 58
66 Quasiquoting The quasiquoting mechanism allows you to embed arbitrary syntax within your Haskell program. And still use Template Haskell s quotation and splicing to mix your object language with Haskell code. This is a mix of the embedded and stand-alone approaches to domain specific languages that we saw over the last few weeks. 59
67 Drawbacks of metaprogramming Metaprogramming has many applications, but several crucial drawbacks: Template Haskell AST and real AST are often out of step. AST is much more complex than S-expressions the Template Haskell library is huge! Debugging type errors in generated code is hard. Q monad allows arbitrary IO during compilation which may be a security risk. Large computations can slow down compile times. 60
68 Looking ahead Student presentations next week. Parallel and concurrent programming in Erlang and Haskell. 61
69 More Functional Programming? Advanced Functional Programming course in the next period. Advanced Functional Programming Summer School in August. Dutch FP day January 5th: Software technology reading club every Friday afternoon. 62
Concepts of programming languages
Concepts of programming languages Lecture 7 Wouter Swierstra 1 Last time Relating evaluation and types How to handle variable binding in embedded languages? 2 DSLs: approaches A stand-alone DSL typically
More informationTemplate Haskell based implementation of printf
Lecture 19 Template Haskell based implementation of printf In the last lecture we saw a type class based solution to create functions that take variable number of arguments. Here we give a template haskell
More informationCSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018
CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures Dan Grossman Autumn 2018 Typical workflow concrete syntax (string) "(fn x => x + x) 4" Parsing Possible errors / warnings
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationCS 360 Programming Languages Interpreters
CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like
More informationThe role of semantic analysis in a compiler
Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationCS1102: Macros and Recursion
CS1102: Macros and Recursion Kathi Fisler, WPI October 5, 2009 This lecture looks at several more macro examples. It aims to show you when you can use recursion safely with macros and when you can t. 1
More informationCSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen
CSE 341 Section 7 Ethan Shea Autumn 2018 Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen Outline Interpreting MUPL Assume Correct Syntax Check for Correct Semantics Evaluating
More informationCSE 341 Section 7. Eric Mullen Spring Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang
CSE 341 Section 7 Eric Mullen Spring 2017 Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang Outline Interpreting LBI (Language Being Implemented) Assume Correct Syntax Check for Correct
More informationConcepts of programming languages
Concepts of programming languages Lecture 2 Wouter Swierstra 1 Last time: programming languages In the first lecture I tried to motivate why we might consider programming languages themselves as interesting
More informationCSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures
CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught
More informationThe Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.
The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees
More informationCase Study: Undefined Variables
Case Study: Undefined Variables CS 5010 Program Design Paradigms Bootcamp Lesson 7.4 Mitchell Wand, 2012-2017 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International
More informationCSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)
CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent
More informationFunctional Programming Lecture 1: Introduction
Functional Programming Lecture 1: Introduction Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague viliam.lisy@fel.cvut.cz Acknowledgements
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationA Functional Evaluation Model
A Functional Evaluation Model COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel A Functional Evaluation Model In order to be able to write a program,
More informationCS 11 Haskell track: lecture 1
CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing
More informationSemantic Analysis. Lecture 9. February 7, 2018
Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average
More informationHaskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.
Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks
More informationForeign Inline Code in Haskell
Foreign Inline Code in Haskell Manuel M T Chakravarty University of New South Wales mchakravarty α TacticalGrace TacticalGrace justtesting.org 30 minute time slot: 25min talking + 5min [15min The Problem;
More informationSemantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far
Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages
More informationCS457/557 Functional Languages
CS457/557 Functional Languages Spring 2018 Lecture 1: Course Introduction Andrew Tolmach Portland State University (with thanks to Mark P. Jones) 1 Goals of this course Introduce the beautiful ideas of
More informationFunctional 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
More informationFunctional 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
More informationCS 360: Programming Languages Lecture 10: Introduction to Haskell
CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia
More informationType families and data kinds
Type families and data kinds AFP Summer School Wouter Swierstra 1 Today How do GADTs work? Kinds beyond * Programming with types 2 Calling functions on vectors Given two vectors xs : Vec a n and ys : Vec
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and
More informationThe Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis
The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed
More informationTypical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated
Typical workflow concrete synta (string) "(fn => + ) 4" Parsing CSE341: Programming Languages abstract synta (tree) Lecture 17 Implementing Languages Including Closures Function Constant + 4 Var Var Type
More informationTrees. Solution: type TreeF a t = BinF t a t LeafF 1 point for the right kind; 1 point per constructor.
Trees 1. Consider the following data type Tree and consider an example inhabitant tree: data Tree a = Bin (Tree a) a (Tree a) Leaf deriving Show tree :: Tree Int tree = Bin (Bin (Bin Leaf 1 Leaf ) 2 (Bin
More informationAnatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?
Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator
More informationLecture C-10: Parser Combinators - Introduction
Lecture C-10: Parser Combinators - Introduction USCS 2015 Doaitse Swierstra Utrecht University July 6-17, 2015 1. Domain Specific Languages 2 Domain Specific Languages 1 A DSL is a programming language
More informationIntermediate Code Generation
Intermediate Code Generation In the analysis-synthesis model of a compiler, the front end analyzes a source program and creates an intermediate representation, from which the back end generates target
More information6.001 Notes: Section 15.1
6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define
More informationTail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)
CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)
More informationHaske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell
Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program
More informationCSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking
CSE450 Translation of Programming Languages Lecture 11: Semantic Analysis: Types & Type Checking Structure Project 1 - of a Project 2 - Compiler Today! Project 3 - Source Language Lexical Analyzer Syntax
More information6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson
6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator
More information1 Lexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler
More informationTyping Data. Chapter Recursive Types Declaring Recursive Types
Chapter 27 Typing Data 27.1 Recursive Types 27.1.1 Declaring Recursive Types We saw in the previous lecture how rec was necessary to write recursive programs. But what about defining recursive types? Recursive
More informationThe name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.
Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More informationCS 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
More informationLecture #24: Programming Languages and Programs
Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware
More informationAbout the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming
About the Tutorial Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional
More informationCIS 194: Homework 3. Due Wednesday, February 11, Interpreters. Meet SImPL
CIS 194: Homework 3 Due Wednesday, February 11, 2015 Interpreters An interpreter is a program that takes another program as an input and evaluates it. Many modern languages such as Java 1, Javascript,
More informationFull file at
Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class
More informationStop coding Pascal. Saturday, April 6, 13
Stop coding Pascal...emotional sketch about past, present and future of programming languages, Python, compilers, developers, Life, Universe and Everything Alexey Kachayev CTO at KitApps Inc. Open source
More informationAn introduction introduction to functional functional programming programming using usin Haskell
An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program
More informationModern Programming Languages. Lecture LISP Programming Language An Introduction
Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation
More informationFunctional programming in LISP
Programming Languages Week 4 Functional programming in LISP College of Information Science and Engineering Ritsumeikan University review of part 3 enumeration of dictionaries you receive a sequence of
More informationCSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.
CSE 341, Spring 2011, Final Examination 9 June 2011 Please do not turn the page until everyone is ready. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.
More informationCSCC24 Functional Programming Scheme Part 2
CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages
More informationChapter 11 :: Functional Languages
Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative
More informationECE220: Computer Systems and Programming Spring 2018 Honors Section due: Saturday 14 April at 11:59:59 p.m. Code Generation for an LC-3 Compiler
ECE220: Computer Systems and Programming Spring 2018 Honors Section Machine Problem 11 due: Saturday 14 April at 11:59:59 p.m. Code Generation for an LC-3 Compiler This assignment requires you to use recursion
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationThe Typed Racket Guide
The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce
More information7. Introduction to Denotational Semantics. Oscar Nierstrasz
7. Introduction to Denotational Semantics Oscar Nierstrasz Roadmap > Syntax and Semantics > Semantics of Expressions > Semantics of Assignment > Other Issues References > D. A. Schmidt, Denotational Semantics,
More informationType Checking and Type Equality
Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.
More informationTerm rewriting a primer
Term rewriting a primer Ralf Lämmel Software Languages Team University of Koblenz-Landau http://www.softlang.org/ Some laws for expressions forms X + 0 = X -- Unit of addition X 1 = X -- Unit of multiplication
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationProgramming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington
Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial
More informationWriting Interpreters Racket eval. CSE341 Section 7. ASTs, Interpreters, MUPL. Sunjay Cauligi. February 21 st, Sunjay Cauligi CSE341 Section 7
Writing Interpreters Racket eval CSE341 Section 7 ASTs, Interpreters, MUPL Sunjay Cauligi February 21 st, 2013 Legal vs. Nonlegal ASTs Consider the Following (add 3 4) (add (const 3) (const 4)) (add (const
More informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
More informationLecture 4 September Required reading materials for this class
EECS 261: Computer Security Fall 2007 Lecture 4 September 6 Lecturer: David Wagner Scribe: DK Moon 4.1 Required reading materials for this class Beyond Stack Smashing: Recent Advances in Exploiting Buffer
More informationIntroduction 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
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More informationLanguage Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */
Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,
More informationConcepts of program design Exam January 31, 13:30 16:30
Concepts of program design 2016 2017 Exam January 31, 13:30 16:30 Name: Student number: Please read the following instructions carefully: Fill in your name and student number above. Be prepared to identify
More informationMetaprogramming assignment 3
Metaprogramming assignment 3 Optimising embedded languages Due at noon on Thursday 29th November 2018 This exercise uses the BER MetaOCaml compiler, which you can install via opam. The end of this document
More informationCSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018
CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is
More informationDocumentation for LISP in BASIC
Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have
More informationCS664 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
More informationParsing Combinators: Introduction & Tutorial
Parsing Combinators: Introduction & Tutorial Mayer Goldberg October 21, 2017 Contents 1 Synopsis 1 2 Backus-Naur Form (BNF) 2 3 Parsing Combinators 3 4 Simple constructors 4 5 The parser stack 6 6 Recursive
More informationFunctional Languages. Hwansoo Han
Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm
More informationLecture 3: Recursion; Structural Induction
15-150 Lecture 3: Recursion; Structural Induction Lecture by Dan Licata January 24, 2012 Today, we are going to talk about one of the most important ideas in functional programming, structural recursion
More informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationCS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise
CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise If you re not already crazy about Scheme (and I m sure you are), then here s something to get
More informationPattern Matching for Scheme
Pattern Matching for Scheme Andrew K. Wright March 1996 Department of Computer Science MS 132 Rice University 6100 Main Street Houston, Texas 77005-1892 Contents 1 Match 1 1.1 Definition... 1 1.1.1 Patterns...
More informationORB Education Quality Teaching Resources
JavaScript is one of the programming languages that make things happen in a web page. It is a fantastic way for students to get to grips with some of the basics of programming, whilst opening the door
More informationScheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.
Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu
More informationProgramming Systems in Artificial Intelligence Functional Programming
Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview
More informationParser Tools: lex and yacc-style Parsing
Parser Tools: lex and yacc-style Parsing Version 6.11.0.6 Scott Owens January 6, 2018 This documentation assumes familiarity with lex and yacc style lexer and parser generators. 1 Contents 1 Lexers 3 1.1
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCSCE 314 Programming Languages. Type System
CSCE 314 Programming Languages Type System Dr. Hyunyoung Lee 1 Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules,.... Names can be
More informationCIS 194: Homework 6. Due Friday, October 17, Preface. Setup. Generics. No template file is provided for this homework.
CIS 194: Homework 6 Due Friday, October 17, 2014 No template file is provided for this homework. Download the markets.json file from the website, and make your HW06.hs Haskell file with your name, any
More informationS206E Lecture 19, 5/24/2016, Python an overview
S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their
More informationProgramming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras
Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras Module 12B Lecture - 41 Brief introduction to C++ Hello, welcome
More informationCPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia
CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques () Lecture 20 February 28, 2018 Transition to Java Announcements HW05: GUI programming Due: THURSDAY!! at 11:59:59pm Lots of TA office hours today Thursday See Piazza
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationFunctional Programming. Big Picture. Design of Programming Languages
Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics
More informationProgramming Paradigms
PP 2017/18 Unit 11 Functional Programming with Haskell 1/37 Programming Paradigms Unit 11 Functional Programming with Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More information4.2 Variations on a Scheme -- Lazy Evaluation
[Go to first, previous, next page; contents; index] 4.2 Variations on a Scheme -- Lazy Evaluation Now that we have an evaluator expressed as a Lisp program, we can experiment with alternative choices in
More informationBeyond JavaScript Frameworks: Writing Reliable Web Apps With. Elm. Erik Wendel DevDays Vilnius 2018
Beyond JavaScript Frameworks: Writing Reliable Web Apps With Elm Erik Wendel DevDays Vilnius 2018 Who is Jonathan Ive? Erik Wendel JavaZone 2017 Elm is like Jonathan Ive would have designed a programming
More informationGADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]
GADTs AFP Summer School Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces: 3 A datatype data
More information