CSE 305 Introduc0on to Programming Languages Lecture 13 Type System (1)

Size: px
Start display at page:

Download "CSE 305 Introduc0on to Programming Languages Lecture 13 Type System (1)"

Transcription

1 CSE 305 Introduc0on to Programming Languages Lecture 13 Type System (1) SUNY- Buffalo Zhi Yang Courtesy of Professor Benjamin C. Pierce Courtesy of Dr. Chung- Chih Li

2 Declara0ons This lecture has majorly referred to on line material Type Systems for Programming Languages, by Benjamin C. Pierce. If you are interested in the official publica0on, please contact the author and Publisher MIT Press. This lecture is mainly focusing on teaching purpose and has nothing to do with any other commercial and academic ac0vi0es.

3 No0ce Board First, we will be pos0ng homework 6 during the weekend, and you can schedule your 0me accordingly. Second, homework5 is due on Monday(July 15, 2013) 11:59pm.

4 Our objec0ve The first objec0ve of our class, is to comprehend a new programming language within very short 5me period, and because you have this ability to shorten your learning curve, you are going to manipulate the language with an insight learning. The second objec0ve is to even engineer your own language!

5 eg: Egyp0an Number System; Complement Number Review what we ve learnt and see future eg: MIPS 2 nd Genera0on language: Assembly Code Number System eg: Gate system, Including different underline device 1 st Genera0on language: Machine Code Regular Expression eg: Abacus Basic Calcula0on System Type Checking eg: Fortran What s next? Lexer Compiler System 3 rd Genera0on Language: Macro func0on Parser Virtual Machine Macro func5on Push Down Automata Context- Free Grammar Lambda Calculus Theory

6 A family tree of languages <Fortran> Cobol <LISP> C BASIC Algol 60 Simula <C++> <Perl> <C#> PL/1 Algol 68 Pascal <Smalltalk> <Java> Modula 3 Dylan <ML> <Scheme> Ada <Ruby> <Python> <JavaScript> <Haskell> <Prolog>

7 Review Concept of Macro A macro (short for "macroinstruc0on", from Greek μακρο- 'long') in computer science is a rule or panern that specifies how a certain input sequence (open a sequence of characters) should be mapped to a replacement input sequence (also open a sequence of characters) according to a defined procedure. The mapping process that instan0ates (transforms) a macro use into a specific sequence is known as macro expansion.

8 What is the rela0on between a macro func0on and Type System Let s look at how microsop MSDN library talks about it. Most Microsop run- 0me library rou0nes are compiled or assembled func0ons, but some rou0nes are implemented as macros. When a header file declares both a func0on and a macro version of a rou0ne, the macro defini0on takes precedence, because it always appears aper the func0on declara0on. When you invoke a rou0ne that is implemented as both a func0on and a macro, you can force the compiler to use the func0on version in two ways: Enclose the rou5ne name in parentheses. #include <ctype.h> //use macro version of toupper a = (toupper)(a); define a = toupper(a); //force compiler to use func5on version of toupper

9 The other version "Undefine" the macro defini0on with the #undef direc0ve: #include <ctype.h> #undef toupper If you need to choose between a func0on and a macro implementa0on of a library rou0ne, consider the following trade- offs: Speed versus size. The main benefit of using macros is faster execu5on 5me. During preprocessing, a macro is expanded (replaced by its defini5on) inline each 5me it is used. A func5on defini5on occurs only once regardless of how many 5mes it is called. Macros may increase code size but do not have the overhead associated with func5on calls. Func0on evalua0on. A func0on evaluates to an address; a macro does not. Thus you cannot use a macro name in contexts requiring a pointer. For instance, you can declare a pointer to a func0on, but not a pointer to a macro.

10 Comparison Macro side effects. A macro may treat arguments incorrectly when the macro evaluates its arguments more than once. For instance, the touppermacro is defined as: #define toupper(c) ( (islower(c))? _toupper(c) : (c) ) In the following example, the toupper macro produces a side effect: #include <ctype.h> int a = 'm'; a = toupper(a++); The example code increments a when passing it to toupper. The macro evaluates the argument a++ twice, once to check case and again for the result, therefore increasing a by 2 instead of 1. As a result, the value operated on by islower differs from the value operated on by toupper. Type- checking. When you declare a func0on, the compiler can check the argument types. Because you cannot declare a macro, the compiler cannot check macro argument types, although it can check the number of arguments you pass to a macro.

11 Type System? A useful though rough dis0nc0on divides the world of programming languages into two parts: Untyped Programs simply execute flat out; there is no anempt to check consistency of shapes Typed some anempt is made, either at compile 0me or at run- 0me, to check shape- consistency.

12 A Brief History of Type

13 A Brief History of Type (Cont.) The earliest type system appears in Fortran.

14 Mathema0cal Preliminaries (Set & Rela0ons)

15 Review Untyped Lambda Basics

16 Formali0es This is an example of an induc5ve defini5on. Since induc0ve defini0ons are ubiquitous in the study of programming languages, it is worth pausing for a moment to examine this one in detail. Here is an alterna0ve defini0on of the same set, in a more concrete style.

17 Set Defini0on

18 Two Defini0ons are equal ~~~T = S

19 Explana0on

20 Constants

21 Size and depth of Term

22 Rela0on between constants and Size

23 Evalua0on

24 Evalua0on Process

25 Proper0es

26 Implementa0on

27 Implementa0on (Cont.)

28 Summary of Type Basics (1)

29 Summary of Type Basics (2)

30 Opera0onal Seman0cs

31 Programming in the Lambda- Calculus

32 Example

33 Grammars

34 Subs0tu0on

35 Solve Problem

36 Solve Problem (Cont.)

37 Opera0onal Seman0cs

38 Summary of Untyped Lambda Calculus

39 Implemen0ng the Lambda- Calculus

40 Defini0on of Terms

41 Shiping and Subs0tu0on

42 Evalua0on

43 A Concrete Realiza0on

44 Evalua0on

45 Typed Arithme0c Expressions

46 The Typing Rela0on

47 Proper0es of Typing and Reduc0on

48 Type Checking

49 Safety = Preserva0on + Progress

50 Implementa0on

51 Summary for boolean and numbers

52 that we shall be studying for the rest of the mily of typedguages lanthe simply typed lambda-calculus of Church [Chu40] and Curry [CF58]. course: the simply typed Simply Typed Lambda- Calculus e family of typed lanse: the simply typed 7.1 Syntax (for brevity, ar: ype mmar: Definition: The set of simple types over the atomic type (for brevity, we omit natural numbers) is generated by the following grammar: (types...) type of functions (types...) type typeof of booleans functions er 7 ::= (types...) type of functions type of booleans type of booleans ly of typed lan. for. e simply typed ly Typed The type constructor Chapter 7 bda-calculus rms (with a-terms (withbooleans booleans (for brevity, is right-associative: stands for. (terms...) (terms...) variable Definition: The abstract syntax of simply typed lambda-terms (with booleans variable abstraction and conditional) is defined by the following grammar: abstraction application ntroduces the most elementary member of the family of typed lan(forconstant brevity, true application we studying for the rest of the course: the simply typed : shall be constant false ::= [CF58]. (terms...) constant trueand Curry lus of Church [Chu40] conditional constant false (types...) variable Chapter 7 conditional type of functions tax Simply Typed Chapter 77 Chapter Lambda-Calculus Simply Typed Typed Simply Chapter 7 Simply Typed type of booleans Lambda-Calculus Lambda-Calculus his chapter introduces the most elementary member of the family of typed lanlambda-calculus uages that.we shall be studying for the rest of the course: the simply typed mbda-calculus of Church [Chu40] and Curry [CF58]. Simply Typed ms (with booleans.1 Syntax Lambda-Calculus er of the family of typed lanhe course: the simply typed ]. on: The set of simple types over the atomic type ral numbers) is langenerated by the following grammar: he family of typed urse: the simply typed (for brevity, This chapter introduces the most elementary member of the family of typed languages that we shall be studying for the rest of the course: the simply typed lambda-calculus of Church [Chu40] and Curry [CF58]. abstraction application constant true constant false conditional (types...) type of functions 7.1 Syntax This the most elementary member ofofthe (types...) Thischapter chapterintroduces introduces the most elementary member thefamily familyofoftyped typedlanlanofsimple booleans Definition:type The set of types over the atomic type (for brevity, type of functions we omit natural numbers) is generated by the following grammar: guages be studying for the guages that that we weshall shall be studying for therest restofofthe thecourse: course: the thesimply simplytyped typed type of booleans ::= (types...) is right-associative: stands. and structor type of functions lambda-calculus ofoffor Church lambda-calculus Church[Chu40] [Chu40] andcurry Curry[CF58]. [CF58]. stands for. type (for brevity, type of booleans 1.1 Definition: The set of simple types over the atomic type (for brevity, (terms...) ammar: is right-associative: stands for. The type constructor (with booleans er:lambda-terms omit numbers) generated the following grammar: on: Thenatural abstract syntax of is simply typedbylambda-terms booleans Definition:(with The abstract syntax of simply typed lambda-terms (with booleans variable (types...) and conditional) is defined by the following grammar: al) is defined by the following grammar: (terms...) ::= (terms...) type of functions 7.1 Syntax 7.1 Syntax ::= (types...) variable This chapter introduces the most elementary member of the family of typed lanabstraction variable type of booleans abstraction abstraction application (terms...) type ofthat functions guages we shall be studying for the rest of the course: the simply typed constant true application application s for types the atomic (for 7.1.1Definition: Definition: The Theset setofofsimple simple types over the atomictype type (forbrevity, brevity, constant variable typeover of booleans constant true lambda-calculus offalsechurch [Chu40] and Curry [CF58]. conditional constant false we weomit omitnatural naturalnumbers) numbers)isisgenerated generatedby bythe thefollowing followinggrammar: grammar: constant true da-terms (with booleans tomic type ing grammar: (for brevity,

53 Conven0on In the literature on type systems, two different presenta0on styles are commonly used: In implicitly typed (or, for historical reasons, Curry- style) systems, the pure (untyped) lambda- calculus is used as the term language. The typing rules define a rela0on between untyped terms and the types that classify them. In explicitly typed (or Church- style) systems, the term language itself is refined so that terms carry some type informa0on within them; for example, the bound variables in func0on abstrac0ons are always annotated with the type of the expected parameter. The type system relates typed terms and their types. To a large degree, the choice is a maner of taste, though explicitly typed systems generally pose fewer algorithmic problems for typecheckers. We will adopt an explicitly typed presenta0on throughout.

54 The Typing Rela0on (1) In order to assign a type to an abstraction like, we need to know what will happen later when it is applied to some argument. The annotation on the bound variable tells us that we may assume that the argument will be of type. In other words, the type of the result will be just the type of, where occurrences of in are assumed to denote terms of type. This intuition is captured by the following rule: (T-ABS) Since, in general, function abstractions can be nested, typing assertions actually have the form, pronounced term has type under the assumptions about the types of its free variables. Formally, the typing context is just a list of variables and their types, and the comma operator extends by concatenating a new binding on the right. To avoid confusion between the new binding and any bindings that may already appear in, we require that the name be chosen so that it does not already appear in dom. (As usual, this condition can always be satisfied by renaming the bound variable if necessary.) can thus be thought of as a finite function from variables to their types. Following this intuition, we will write dom for the set of variables bound by and for the type associated with in. So the rule for typing abstractions actually has the general form where the premise adds one more assumption to those in the conclusion. (T-ABS)

55 The Typing Rela0on (2) The typing rule for variables follows immediately from this discussion. A variable has whatever type we are currently assuming it to have: Next, we need a rule for application: (T-VAR) (T-APP) In English: If evaluates to a function mapping arguments in to results in (under the assumption that the terms represented by its free variables yield results of the types associated to them by ), and if evaluates to a result in, then the result of applying to will be a value of type. We have now given typing rules for each of the individual constructs in our simple language. To assign types to whole programs, we combine these rules into derivation trees. For example, here is a derivation tree showing that the term has type in the empty context: T-VAR T-ABS T-TRUE T-APP Exercise [Quick check]: Show (by exhibiting derivation trees) that the fol-

56 Syntax Summary for Simply Typed Lambda- Calculus : Simply typed lambda-calculus (typed) ::= (terms...) variable abstraction application ::= (values...) abstraction value ::= (types...) type of functions ::= (contexts...) empty context term variable binding Evaluation ( ) (E-BETA) (E-APP1) (E-APP2) Typing ( ) (T-VAR) (T-ABS) (T-APP)

57 Proper0es of Typing and Reduc0on (1) Theorem [Uniqueness of Types]: In a given typing context, a term (with free variables all in the domain of ) has at most one type. That is, if a term is typeable, then its type is unique. Moreover, there is just one derivation of this typing built from the inference rules that generate the typing relation. The proof of the uniqueness theorem is so direct that there is almost nothing to say. We present a few cases carefully just to illustrate the structure of proofs by induction on typing derivations. Proof: Suppose that and. We show, by induction on a derivation of, that. Case T-VAR: with By case (1) of the inversion lemma (7.4.1), the final rule in any derivation of must also be T-VAR, and. Case T-ABS: By case (2) of the inversion lemma, the final rule in any derivation of must also be T-ABS, and this derivation must have a subderivation with conclusion, with. By the induction hypothesis (on the subderivation with conclusion ( ), we obtain, from which is immediate. Case T-APP, T-TRUE, T-FALSE, T-IF: Similar.

58 Proper0es of Typing and Reduc0on (1) Typechecking Lemma [Inversion of the typing relation]: 1. If, then. 2. If, then and. 3. If, then there is some type such that and. 4. If, then. 5. If, then. 6. If, then

59 Typing and Subs0tu0on Lemma [Substitution]: If and, then Theorem [Preservation of types during evaluation]: If and, then Theorem [Progress]: Suppose is closed and stuck. If, then is a value.

60 Implementa0on

61 Base types Extensions (1) New syntactic forms ::=... (types...) base type Unit type New syntactic forms ::=... (terms...) constant ::=... (types...) Let binding New syntactic forms ::=... (terms...) let binding New evaluation rules ( ) (E-LETBETA) (E-LET) New typing rules ( ) (T-LET)

62 Extensions (2) Records and tuples New syntactic forms ::=... (terms...) record projection ::=... (values...) record value ::=... (types...) type of records New evaluation rules ( ) (E-RCDBETA) (E-PROJ) (E-RECORD) New typing rules ( ) for each (T-RCD) (T-PROJ) New abbreviations def def Exercise: In this presentation of records, the projection operation is used to

63 Extensions (3) Record patterns New syntactic forms ::= pat (untyped) variable pattern record pattern ::=... (terms...) pattern binding Matching rules: match (M-VAR) match for each match (M-RCD) New evaluation rules ( ) match (E-LETBETA) (E-LET) New abbreviations def

64 Extensions (4) Variants New syntactic forms ::=... (terms...) tagging case ::=... (types...) type of variants New evaluation rules ( ) (E-CASEBETA) (E-CASE) (E-TAG) New typing rules ( ) for each (T-VARIANT) for each (T-CASE)

65 General recursion New syntactic forms Extensions (5) ::=... (terms...) fixed point of New typing rules ( ) (T-FIX) New abbreviations def

66 Lists New syntactic forms Extensions (6) ::=... (terms...) empty list list constructor test for empty list head of a list tail of a list ::=... (values...) empty list list constructor ::=... (types...) type of lists New evaluation rules ( ) New typing rules ( ) (E-CONS1) (E-CONS2) (E-NULLBETAT) (E-NULLBETAF) (E-NULL) (E-HEADBETA) (E-HEAD) (E-TAILBETA) (E-TAIL) (T-NIL) (T-CONS) (T-NULL) (T-HEAD) (T-TAIL)

67 Lazy let bindings New syntactic forms Extensions (7) ::=... (terms...) lazy let binding New evaluation rules ( ) New typing rules ( ) (E-LLETBETA) (T-LLET) Lazy records New syntactic forms ::=... (terms...) lazy record ::=... (values...) lazy record value New evaluation rules ( ) New typing rules ( ) (E-LRCDBETA) (T-LRCD)

68 ML Download SML here Robin Milner Meta Language One of the most popular functional languages Edinburgh, 1974, Robin Milner s group There are a number of dialects with Lockwood Morris We are using Standard ML (SML) but we will just call it ML from the time being Turing Award 1991

69 SML/NJ Standard ML of New Jersey (abbreviated SML/NJ) is a compiler for the Standard ML '97 programming language with associated libraries, tools, and documenta0on. SML/NJ is free, open source sopware. hnp:// You are encourage to install SML/NJ on your computer, but we are going to use the one installed in our Unix server Timberlake, and all your work will be tested there. But you can write your code on any platform, just let me know what it is.

70 Standard ML of New Jersey *3; val it = 7 : int -1+2*3 = = ; val it = 7 : int - prompt Expression (; is not part of the expression.) ML replies with value and type = means that ML expects more input it needs ; to end the expression Variable it is a special variable bound to the value of the expression just typed

71 ML Basic (the building blocks) Constants Operators Defining Variables Tuples and Lists Defining Functions ML Types and Type Annotations

72 Mottoes of ML Type is the backbone of ML Recursion is the blood of ML Function is the flesh of ML Higher order is the soul of ML

73 - 1234; val it = 1234 : int ; val it = : real Integer constants: standard integers, Real constants: standard decimal notation int, real are the names of the types

74 - true; val it = true : bool - false; val it = false : bool Boolean constants true and false ML is case-sensitive: use true, not True or TRUE Type name: bool

75 - "fred"; val it = "fred" : string - "H"; val it = "H" : string - #"H"; val it = #"H" : char String constants: text inside double quotes Can use C-style escapes: \n, \t, \\, \", etc. Character constants: put # before a 1-character string Type names: string and char

76 - ~ * 4 div 5 mod 6; val it = ~1 : int - Operators Standard operators for integers ~ (tilde) for unary negation, e.g., ~1, negative 1 - for binary subtraction - ~ * 4.0 / 5.0; val it = ~1.4 : real - Same operators for reals, (use / for real division) Left associative, precedence is {+,-} < {*,/,div, mod} < {~}.

77 - "bibity" ^ "bobity" ^ "boo"; val it = "bibitybobityboo" : string - 2 < 3; val it = true : bool <= 1.0; val it = true : bool - #"d" > #"c"; val it = true : bool - "abce" >= "abd"; val it = false : bool String concatenation: ^ operator Ordering comparisons: <, >, <=, >=, apply to string, char, int and real Order on strings and characters is lexicographic

78 - 1 = 2; val it = false : bool - true <> false; val it = true : bool = 1.3; Error: operator and operand don't agree [equality type required] operator domain: ''Z * ''Z operand: real * real in expression: 1.3 = 1.3 Equality comparisons: = and <> Most types are equality testable: these are equality types Type real is not an equality type

79 - 1 < 2 orelse 3 > 4; val it = true : bool - 1 < 2 andalso not (3 < 4); val it = false : bool Boolean operators: andalso, orelse, not. And we can also use = for equivalence <> for exclusive or.

80 Precedence:: ~ not * / div mod + - ^ = <> < > <= >= Andalso orelse

81 - true orelse 1 div 0 = 0; val it = true : bool Note: andalso and orelse are short-circuiting operators. E.g., if the first operand of orelse is true, the second is not evaluated; likewise if the first operand of andalso is false Technically, they are not ML operators, but keywords Because all true ML operators evaluate all operands

82 - if 1 < 2 then #"x" else #"y ; val it = #"x" : char -if 1 > 2 then 34 else 56; val it = 56 : int - (if 1 < 2 then 34 else 56) + 1; val it = 35 : int Conditional expression (not statement) using if then else Similar to C's ternary operator: (1<2)? 'x' : 'y' Value of the expression is the value of the then part, if the test part is true, or the value of the else part otherwise There is no if then construct

83 What is the value and ML type for each of the following expressions? 1 * * 4 "abc" ^ "def" if (1 < 2) then 3.0 else < 2 orelse (1 div 0) = 0 Practice What is wrong? 10 / 5 #"a" = #"b" or 1 = = 1.0 if (1<2) then 3 else 4.0 If (1<2) then 3

84 - 1 * 2; val it = 2 : int * 2.0; val it = 2.0 : real * 2; Error: operator and operand don't agree [literal] operator domain: real * real operand: real * int in expression: 1.0 * 2 The * operator, and others like + and <, are overloaded to have one meaning on pairs of integers, and another on pairs of reals ML does not perform implicit type conversion

85 - real(123); val it = : real - floor(3.6); val it = 3 : int - floor 3.6; val it = 3 : int - str #"a"; val it = "a" : string Some Built-in conversion functions: 1. real (fn: int à real) 2. floor (fn: real à int) 3. ceil (fn: real à int) 4. round (fn: real à int) 5. trunc (fn: real à int) 6. ord (fn: char à int) 7. chr (fn: int à char) 8. str (fn: char à string)

86 Function Associativity Function application is left-associative So f a b means (f a) b, which means: first apply f to the single argument a; then take the value f returns, which should be another function; then apply that function to b f g h i j ((((f g) h) i) j) Note: This is different from function composition: f(g(h(i(j))))

87 - square 2+1; val it = 5 : int - square (2+1); val it = 9 : int Function application has higher precedence than any operator square 2+1; (square 2) + 1;

88 Practice What if anything is wrong with each of the following expressions? trunc 5 chr ord "a" str if 0 then 1 else 2 if true then 1 else 2.0 chr(trunc(97.0)) chr(trunc 97.0) chr trunc 97.0 trunc (fn: real à int) ord (fn: char à int) (fn: int à char) (fn: char à string)

89 Defining Variables - val x = 1+2*3; - val x = 7 : int - x; val it = 7 : int - val y = if x = 7 then 1.0 else 2.0; val y = 1.0 : real Val defines a new variable and bind it to a value. Variable names should consist of a letter, followed by zero or more letters, digits, and/or underscores.

90 - val fred = 23; val fred = 23 : int - fred; val it = 23 : int - val fred = true; val fred = true : bool - fred; val it = true : bool You can define a new variable with the same name as an old one, even using a different type. This is not the assignment. It defines a new variable but does not change the old one; it s a declaration. This example is not particularly useful ; - Same as type in: - val it = 1+2+3; Any part of the program that was using the first definition of fred, still is after the second definition is made.

91 Practice Suppose we make these ML declarations in the following order: val a = "123"; val b = "456"; val c = a ^ b ^ "789"; val a = 3 + 4; Then, what is the values and types of a, b, and c after the last expression above? a b c 7 "456" " "

92 Suppose we make these ML declarations: - val a = 3; Not an assignment - fun f x = x + a; - val a = 4; This is a way we define a function. (flesh) - fun g x = x + a; Then, what are the following results? - g 2; - f 2; 6 5

93 Garbage Collection Sometimes, for no apparent reason, we see GC # : (0 ms) A garbage collection has been performed.

94 Tuples and Lists Two most important structures in ML Tuples : (1,2,3) Lists: [1, 2, 3] Like a struct Like an array

95 Tuples 1. A tuple is like a record (struct) with no field names 2. Use parentheses to form tuples 3. Tuples can contain other tuples 4. To get i th element of a tuple x, use #i x - val barney = (1+2, 3.0*4.0, "brown"); val barney = (3,12.0,"brown") : int * real * string - val point1 = ("red", (300,200)); val point1 = ("red",(300,200)) : string * (int * int) - #2 barney; val it = 12.0 : real - #1 (#2 point1); val it = 300 : int

96 (1) is not a tuple of one - (1, 2); val it = (1,2) : int * int - (1); val it = 1 : int - #1 (1, 2); val it = 1 : int - #1 (1); Error: operator and operand don't agree [literal] operator domain: {1:'Y; 'Z} operand: int in expression: (fn {1=1,...} => 1) 1

97 Tuple Type Constructor ML gives the type of a tuple using * as a type constructor For example, int * bool is the type of pairs (x,y) where x is an int and y is a bool Note that parentheses have structural significance: Cartesian Products: int * (int * bool) (int * int) * bool int * int * bool A= {a, b} B={1, 2, 3} A B = {(a,1), (a,2), (a,3), (b,1), (b,2), (b,3)}

98 Lists Use square brackets to make lists Unlike tuples, all elements of a list must be of the same type - [1,2,3]; val it = [1,2,3] : int list - [1.0,2.0]; val it = [1.0,2.0] : real list - [true]; val it = [true] : bool list - [(1,2),(1,3)]; val it = [(1,2),(1,3)] : (int * int) list - [[1,2,3],[1,2]]; val it = [[1,2,3],[1,2]] : int list list Elements in a list must have the same type

99 - []; val it = [] : 'a list - nil; val it = [] : 'a list Empty list is [] or nil Note the unknown type of the empty list: 'a list Any variable name beginning with an apostrophe is a type variable; it stands for a type that is unknown 'a list means a list of elements with type unknown

100 The null test - null []; val it = true : bool - null [1,2,3]; val it = false : bool null tests whether a given list is empty You could also use an equality test, as in x = [] However, null x is preferred; (we will see why in a moment)

101 List Type Constructor ML gives the type of lists using list as a type constructor For example, int list is the type of lists of type int A list is not a tuple

102 - val it = [1,2,3,4,5,6] : int list operator concatenates lists Operands are two lists of the same type Equivalence, [1]@[2,3,4] or 1::[2,3,4] Note: 1@[2,3,4] is wrong

103 - val x = #"c"::[]; val x = [#"c"] : char list - val y = #"b"::x; val y = [#"b",#"c"] : char list - val z = #"a"::y; val z = [#"a",#"b",#"c"] : char list List-builder operator is :: (cons) Lisp It puts the new element on the front of the old list, the types must be agreed.

104 - val z = 1::2::3::[]; val z = [1,2,3] : int list - hd z; val it = 1 : int - tl z; val it = [2,3] : int list -tl(tl z); val it = [3] : int list -tl(tl(tl z)); val it = [] : int list The :: operator is right-associative hd : the first element tl : the tail; the whole list after the first element

105 Practice What are the values of the following expressions? #2(3,4,5) hd(1::2::nil) hd(tl(#2([1,2],[3,4]))) What is wrong with the following expressions? hd(tl(tl [1,2])) [1]::[2,3]

106 explode : converts a string to a list of characters implode : converts a list of characters to a string - explode "hello"; val it = [#"h",#"e",#"l",#"l",#"o"] : char list - implode [#"h",#"i"]; val it = "hi" : string - explode; val it = fn : string -> char list - implode; val it = fn : char list -> string - hd; val it = fn : 'a list -> 'a - tl; val it = fn : 'a list -> 'a list -

107 Moco Type is the backbone of ML Recursion is the blood of ML Function is the flesh of ML Higher order is the soul of ML ML is constructed based on types (backbone) ML carries information by recursion (blood) ML s outlook is made by function (flesh) ML exists because of its higher order computation (soul)

108 Defining Func0ons fun defines a new func0on and binds it to a variable. Func0on is a type, thus fun is a type constructor. Now, suppose we want to define a func5on that will take a string and return its first character. - fun firstchar s = hd (explode s); val firstchar = fn : string -> char - firstchar "abc"; val it = #"a" : char It is rarely necessary to declare any types, since ML infers them. ML can tell that s must be a string, since we used explode on it, and it can tell that the function result must be a char, since it is the hd of a char list

109 Function Definition Syntax in BNF <fun-def> ::= fun <function-name> <parameter> = <expression> ; <function-name> can be any legal ML name The simplest <parameter> is just a single variable name: the formal parameter of the function The <expression> is any ML expression; its value is the value the function returns This is a subset of ML function definition syntax; Func0on Type Constructor E.g., int -> real is the type of a function that takes an int parameter, the domain type) and produces a real result, the range (co-domain) type

110 All ML functions take exactly one parameter To pass more than one thing, you can pass a tuple - fun quot(a,b) = a div b; val quot = fn : int * int -> int - quot (6,2); val it = 3 : int - val pair = (6,2); val pair = (6,2) : int * int - quot pair; val it = 3 : int

111 Recursive factorial function Motto: Type is the backbone of ML Recursion is the blood of ML Function is the flesh of ML Higher order is the soul of ML - fun fact n = = if n = 0 then 1 = else n * fact(n-1); val fact = fn : int -> int - fact 5; val it = 120 : int

112 Recursive func0on to add up the elements of an int list - fun listsum x = = if null x then 0 = else hd x + listsum(tl x); val listsum = fn : int list -> int - listsum [1,2,3,4,5]; val it = 15 : int This function has used a common pattern: 1. base case for null x, 2. recursive call on tl x

113 Recursive func0on to compute the length of a list (This is predefined in ML) - fun length x = = if null x then 0 = else 1 + length (tl x); val length = fn : 'a list -> int - length [true,false,true]; val it = 3 : int - length [4.0,3.0,2.0,1.0]; val it = 4 : int Note type: this works on any type of list. It is polymorphic.

114 - fun badlength x = = if x=[] then 0 = else 1 + badlength (tl x); val badlength = fn : ''a list -> int - badlength [true,false,true]; val it = 3 : int - badlength [4.0,3.0,2.0,1.0]; Error: operator and operand don't agree [equality type required] two apostrophes, like ''a, are restricted to equality types, because we compared x for equality with the empty list. That s why null x is better than x=[]. It avoids unnecessary type restrictions.

115 Recursive function to reverse a list - fun reverse L = = if null L then nil = else reverse(tl [hd L]; val reverse = fn : 'a list -> 'a list - reverse [1,2,3]; val it = [3,2,1] : int list

116 ML Types and Type Annotations Primitive types: int, real, bool, char, and string Three type constructors: Tuple types using * List types using list Function types using ->

117 Constructor s precedence When combining constructors, list >> * >> -> int * bool list int * (bool list) int * bool list -> real (int * (bool list)) -> real Use parentheses as necessary for clarity

118 - fun prod(a,b) = a * b; val prod = fn : int * int -> int Why int, rather than real? ML s default type for * (and +, and ) is int * int -> int You can give an explicit type annotation to get real instead

119 - fun prod(a:real,b:real):real = a*b; val prod = fn : real * real -> real Type annotation is a colon followed by a type Can appear after any variable or expression These are all equivalent: fun prod(a,b):real = a * b; fun prod(a:real,b) = a * b; fun prod(a,b:real) = a * b; fun prod(a,b) = (a:real) * b; fun prod(a,b) = a * b:real; fun prod(a,b) = (a*b):real; fun prod((a,b):real * real) = a*b;

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called CS109A ML Notes for the Week of 1/16/96 Using ML ML can be used as an interactive language. We shall use a version running under UNIX, called SML/NJ or \Standard ML of New Jersey." You can get SML/NJ by

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

Course outline. CSE 341: Programming Languages. Why study programming languages? Course motivation and objectives. 1 lecture: Concepts

Course outline. CSE 341: Programming Languages. Why study programming languages? Course motivation and objectives. 1 lecture: Concepts CSE 341: Programming Languages Course outline Explore several other programming paradigms 1 lecture: Concepts ML, Scheme,...: functional programming, lists, recursion, pattern-matching, polymorphic typing,

More information

F28PL1 Programming Languages. Lecture 11: Standard ML 1

F28PL1 Programming Languages. Lecture 11: Standard ML 1 F28PL1 Programming Languages Lecture 11: Standard ML 1 Imperative languages digital computers are concrete realisations of von Neumann machines stored program memory associations between addresses and

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Note that pcall can be implemented using futures. That is, instead of. we can use

Note that pcall can be implemented using futures. That is, instead of. we can use Note that pcall can be implemented using futures. That is, instead of (pcall F X Y Z) we can use ((future F) (future X) (future Y) (future Z)) In fact the latter version is actually more parallel execution

More information

CS558 Programming Languages

CS558 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 information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 1. true / false By a compiler we mean a program that translates to code that will run natively on some machine. 2. true / false ML can be compiled. 3. true / false FORTRAN can reasonably be considered

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

Programming Languages Third Edition

Programming Languages Third Edition Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand

More information

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of If we have a call (map slow-function long-list where slow-function executes slowly and long-list is a large data structure, we can expect to wait quite a while for computation of the result list to complete.

More information

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont.

Dialects of ML. CMSC 330: Organization of Programming Languages. Dialects of ML (cont.) Features of ML. Functional Languages. Features of ML (cont. CMSC 330: Organization of Programming Languages OCaml 1 Functional Programming Dialects of ML ML (Meta Language) Univ. of Edinburgh,1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

CIS24 Project #3. Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec. Subject: Functional Programming Language (ML)

CIS24 Project #3. Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec. Subject: Functional Programming Language (ML) CIS24 Project #3 Student Name: Chun Chung Cheung Course Section: SA Date: 4/28/2003 Professor: Kopec Subject: Functional Programming Language (ML) 1 Introduction ML Programming Language Functional programming

More information

Haskell: 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, 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 information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

G Programming Languages - Fall 2012

G 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 information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

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) 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

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional 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 information

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming

Introduction to ML. Mooly Sagiv. Cornell CS 3110 Data Structures and Functional Programming Introduction to ML Mooly Sagiv Cornell CS 3110 Data Structures and Functional Programming Typed Lambda Calculus Chapter 9 Benjamin Pierce Types and Programming Languages Call-by-value Operational Semantics

More information

Chapter 11 :: Functional Languages

Chapter 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 information

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

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:

More information

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy

Polymorphic lambda calculus Princ. of Progr. Languages (and Extended ) The University of Birmingham. c Uday Reddy 06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 6: Polymorphic Type Systems 1. Polymorphic

More information

Lesson 4 Typed Arithmetic Typed Lambda Calculus

Lesson 4 Typed Arithmetic Typed Lambda Calculus Lesson 4 Typed Arithmetic Typed Lambda 1/28/03 Chapters 8, 9, 10 Outline Types for Arithmetic types the typing relation safety = progress + preservation The simply typed lambda calculus Function types

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

A quick introduction to SML

A quick introduction to SML A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important

More information

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Functional Programming

Functional Programming Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Formal Systems and their Applications

Formal Systems and their Applications Formal Systems and their Applications Dave Clarke (Dave.Clarke@cs.kuleuven.be) Acknowledgment: these slides are based in part on slides from Benjamin Pierce and Frank Piessens 1 Course Overview Introduction

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a

More information

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

More information

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

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

More information

Types. What is a type?

Types. What is a type? Types What is a type? Type checking Type conversion Aggregates: strings, arrays, structures Enumeration types Subtypes Types, CS314 Fall 01 BGRyder 1 What is a type? A set of values and the valid operations

More information

Lecture 2: The Basis of SML

Lecture 2: The Basis of SML Lecture 2: The Basis of SML Jean-Noël Monette Functional Programming 1 September 9, 2013 Based on notes by Pierre Flener, Sven-Olof Nyström Jean-Noël Monette (UU) Lecture 2: The Basis of SML 1 / 73 Today

More information

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e

More information

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

Programming Paradigms Languages F28PL, Lecture 1

Programming Paradigms Languages F28PL, Lecture 1 Programming Paradigms Languages F28PL, Lecture 1 Jamie Gabbay October 14, 2016 1 / 37 About me My name is Murdoch James Gabbay everybody calls me Jamie. I got a PhD in Cambridge in 2001. Since then I have

More information

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

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

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Introduc)on To Standard ML

Introduc)on To Standard ML The ML Programming Language Introduc)on To Standard ML CS251 Programming Languages Spring 2018 Lyn Turbak Department of Computer Science Wellesley College ML (Meta Language) was developed by Robin Milner

More information

Type Checking and Type Inference

Type Checking and Type Inference Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

More information

The Substitution Model

The Substitution Model The Substitution Model Prof. Clarkson Fall 2017 Today s music: Substitute by The Who Review Previously in 3110: simple interpreter for expression language abstract syntax tree (AST) evaluation based on

More information

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

More information

4/19/2018. Chapter 11 :: Functional Languages

4/19/2018. Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

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

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

More information

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

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

More information

Com S 541. Programming Languages I

Com S 541. Programming Languages I Programming Languages I Lecturer: TA: Markus Lumpe Department of Computer Science 113 Atanasoff Hall http://www.cs.iastate.edu/~lumpe/coms541.html TR 12:40-2, W 5 Pramod Bhanu Rama Rao Office hours: TR

More information

Related Course Objec6ves

Related Course Objec6ves Syntax 9/18/17 1 Related Course Objec6ves Develop grammars and parsers of programming languages 9/18/17 2 Syntax And Seman6cs Programming language syntax: how programs look, their form and structure Syntax

More information

CS 11 Haskell track: lecture 1

CS 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 information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

Introduction to lambda calculus Part 3

Introduction to lambda calculus Part 3 Introduction to lambda calculus Part 3 Antti-Juhani Kaijanaho 2017-01-27... 1 Untyped lambda calculus... 2 Typed lambda calculi In an untyped lambda calculus extended with integers, it is required that

More information

Functional Languages. Hwansoo Han

Functional 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 information

Introduction. chapter Functions

Introduction. chapter Functions chapter 1 Introduction In this chapter we set the stage for the rest of the book. We start by reviewing the notion of a function, then introduce the concept of functional programming, summarise the main

More information

Programming Languages Fall 2014

Programming Languages Fall 2014 Programming Languages Fall 2014 Lecture 7: Simple Types and Simply-Typed Lambda Calculus Prof. Liang Huang huang@qc.cs.cuny.edu 1 Types stuck terms? how to fix it? 2 Plan First I For today, we ll go back

More information

Functional Programming

Functional Programming Functional Programming Function evaluation is the basic concept for a programming paradigm that has been implemented in functional programming languages. The language ML ( Meta Language ) was originally

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 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 information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-19: Type

More information

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML CMSC 330: Organization of Programming Languages Functional Programming with OCaml 1 Background ML (Meta Language) Univ. of Edinburgh, 1973 Part of a theorem proving system LCF The Logic of Computable Functions

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

CS4215 Programming Language Implementation. Martin Henz

CS4215 Programming Language Implementation. Martin Henz CS4215 Programming Language Implementation Martin Henz Thursday 26 January, 2012 2 Chapter 4 The Language simpl In this chapter, we are exting the language epl in order to provide a more powerful programming

More information

So what does studying PL buy me?

So what does studying PL buy me? So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chicken-and-egg. My goal: educate tomorrow s tech leaders

More information

(Refer Slide Time: 4:00)

(Refer Slide Time: 4:00) Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Example Scheme Function: equal

Example Scheme Function: equal ICOM 4036 Programming Languages Functional Programming Languages Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: LISP Introduction to

More information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail 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 information

Programming Language Pragmatics

Programming Language Pragmatics Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

More information

CS 565: Programming Languages. Spring 2008 Tu, Th: 16:30-17:45 Room LWSN 1106

CS 565: Programming Languages. Spring 2008 Tu, Th: 16:30-17:45 Room LWSN 1106 CS 565: Programming Languages Spring 2008 Tu, Th: 16:30-17:45 Room LWSN 1106 Administrivia Who am I? Course web page http://www.cs.purdue.edu/homes/peugster/cs565spring08/ Office hours By appointment Main

More information

Haskell 98 in short! CPSC 449 Principles of Programming Languages

Haskell 98 in short! CPSC 449 Principles of Programming Languages Haskell 98 in short! n Syntax and type inferencing similar to ML! n Strongly typed! n Allows for pattern matching in definitions! n Uses lazy evaluation" F definition of infinite lists possible! n Has

More information

Chapter 2 SML, a Functional Programming Language

Chapter 2 SML, a Functional Programming Language Plan Chapter 2 SML, a Functional Programming Language 1. Expressions... 2.2 2. Value declarations... 2.13 3. Function declarations... 2.16 4. Type inference... 2.18 5. Anonymous functions... 2.20 6. Specifications...

More information

2.1. Expressions. Chapter 2 SML, a Functional Programming Language. Integers. Interacting with ML

2.1. Expressions. Chapter 2 SML, a Functional Programming Language. Integers. Interacting with ML Plan Chapter 2 SML, a Functional Programming Language 1. Expressions... 2.2 2. Value declarations... 2.13 3. Function declarations... 2.16 4. Type inference... 2.18 5. Anonymous functions... 2.20 6. Specifications...

More information

Programming Systems in Artificial Intelligence Functional Programming

Programming 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 information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 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 information

Simply-Typed Lambda Calculus

Simply-Typed Lambda Calculus #1 Simply-Typed Lambda Calculus #2 Back to School What is operational semantics? When would you use contextual (small-step) semantics? What is denotational semantics? What is axiomatic semantics? What

More information

SMURF Language Reference Manual Serial MUsic Represented as Functions

SMURF Language Reference Manual Serial MUsic Represented as Functions SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu

More information

Final-Term Papers Solved MCQS with Reference

Final-Term Papers Solved MCQS with Reference Solved MCQ(S) From FinalTerm Papers BY Arslan Jan 14, 2018 V-U For Updated Files Visit Our Site : Www.VirtualUstaad.blogspot.com Updated. Final-Term Papers Solved MCQS with Reference 1. The syntax of PHP

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

Second release of the COMPASS Tool Tool Grammar Reference

Second release of the COMPASS Tool Tool Grammar Reference Grant Agreement: 287829 Comprehensive Modelling for Advanced Systems of Systems Second release of the COMPASS Tool Tool Grammar Reference Deliverable Number: D31.2c Version: 1.2 Date: January 2013 Public

More information

SPARK-PL: Introduction

SPARK-PL: Introduction Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...

More information

Flang typechecker Due: February 27, 2015

Flang typechecker Due: February 27, 2015 CMSC 22610 Winter 2015 Implementation of Computer Languages I Flang typechecker Due: February 27, 2015 Project 3 February 9, 2015 1 Introduction The third project is to implement a type checker for Flang,

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Lecture 9: Typed Lambda Calculus

Lecture 9: Typed Lambda Calculus Advanced Topics in Programming Languages Spring Semester, 2012 Lecture 9: Typed Lambda Calculus May 8, 2012 Lecturer: Mooly Sagiv Scribe: Guy Golan Gueta and Shachar Itzhaky 1 Defining a Type System for

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages. Spring 2015 CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

More information

More Untyped Lambda Calculus & Simply Typed Lambda Calculus

More Untyped Lambda Calculus & Simply Typed Lambda Calculus Concepts in Programming Languages Recitation 6: More Untyped Lambda Calculus & Simply Typed Lambda Calculus Oded Padon & Mooly Sagiv (original slides by Kathleen Fisher, John Mitchell, Shachar Itzhaky,

More information

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu

More information

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually Plan (next 4 weeks) 1. Fast forward Rapid introduction to what s in OCaml 2. Rewind 3. Slow motion Go over the pieces individually History, Variants Meta Language Designed by Robin Milner @ Edinburgh Language

More information

CS 242. Fundamentals. Reading: See last slide

CS 242. Fundamentals. Reading: See last slide CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

More information