Data Types The ML Type System

Size: px
Start display at page:

Transcription

1 7 Data Types The ML Type System The following is an ML version of the tail-recursive Fibonacci function introduced Fibonacci function in ML in Section 6.6.1: EXAMPLE fun fib (n) = 2. let fun fib_helper (f1, f2, i) = 3. if i = n then f2 4. else fib_helper (f2, f1+f2, i+1) 5. in 6. fib_helper (0, 1, 0) 7. end; EXAMPLE 7.97 Expression types The let construct introduces a nested scope: function fib_helper is nested inside fib. The body of fib is the expression fib_helper (0, 1, 0). The body of fib_helper is an if...then...else expression; it evaluates to either f2 or to fib_helper (f2, f1+f2, i+1), depending on whether the third argument to fib_helper is n or not. Given this function definition, an ML compiler will reason roughly as follows: Parameter i of fib_helper must have type int, because it is added to 1 at line 4. Similarly, parameter n of fib must have type int, because it is compared to i at line 3. In the specific call to fib_helper at line 6, the types of all three arguments are int, so in this context at least, the types of f1 and f2 are int. Moreover the type of i is consistent with the earlier inference, namely int, and the types of the arguments to the recursive call at line 4 are similarly consistent. Since fib_helper returns f2 at line 3, the result of the call at line 6 will be an int. Since fib immediately returns this result as its own result, the return type of fib is int. Because ML is a functional language, every construct in ML is an expression. The ML type system infers a type for every object and every expression. Because functions are first-class values, they too have types. The type of fib above is int -> int; that is, a function from integers to integers. The type of fib_helper is 125

2 126 Chapter 7 Data Types EXAMPLE 7.98 Type inconsistency int * int * int -> int; that is, a function from integer triples to integers. In denotational terms, int * int * int is a three-way Cartesian product. Type correctness in ML amounts to what we might call type consistency: a program is type correct if the type checking algorithm can reason out a unique type for every expression, with no contradictions and no ambiguous occurrences of overloaded names. (For built-in arithmetic and comparison operators, ML assumes that arguments are integers if it cannot determine otherwise. Haskell is a bit more general: it allows the arguments to be of any type that supports the required operations.) If the programmer uses an object inconsistently, the compiler will complain. In a program containing the following expressions, fun circum (r) = r * 2.0 * ;... circum (7) EXAMPLE 7.99 Polymorphic functions the compiler will infer that circum s parameter is of type real, and will then complain when we attempt to pass an integer argument. Though usually compiled instead of interpreted, ML is intended for interactive use. The programmer interacts with the ML system on-line, giving it input a line at a time. The system compiles this input incrementally, binding machine language fragments to function names, and producing any appropriate compiletime error messages. This style of interaction blurs the traditional distinction between interpretation and compilation, but has more of the flavor of the latter. The language implementation remains active during program execution, but it does not actively manage the execution of program fragments: it transfers control to them and waits for them to return. In comparison to languages in which programmers must declare all types explicitly, ML s type inference system has the advantage of brevity and convenience for interactive use. More important, it provides a powerful form of implicit parametric polymorphism more or less for free. While all uses of objects in an ML program must be consistent, they do not have to be completely specified: fun compare (x, p, q) = if x = p then if x = q then "both" else "first" else if x = q then "second" else "neither"; Here the equality test (=) is a built-in polymorphic function of type a* a -> bool; that is, a function that takes a pair of arguments of the same type and produces a Boolean result. The token a is called a type variable; it stands for any type, and takes, implicitly, the role of an explicit type parameter in a generic construct (Sections 8.4 and 9.4.4). Every instance of a in a given call to = must represent the same type, but instances of a in different calls can be different. Starting with the type of =, an ML compiler can reason that the type of

3 7.2.4 The ML Type System 127 compare is a * a * a -> string.thuscompare is polymorphic; it does not depend on the types of x, p, and q, so long as they are all the same. The key point to observe is that the programmer did not have to do anything special to make compare polymorphic: polymorphism is a natural consequence of ML-style type inference. Type Checking An ML compiler verifies type consistency with respect to a well-defined set of constraints. Specifically, All occurrences of the same identifier (subject to scope rules) must have the same type. In an if... then... else expression, the condition must be of type bool, and the then and else clauses must have the same type. A programmer-defined function has type a -> b, where a is the type of the function s parameter, and b is the type of its result. As we shall see shortly, all functions have a single parameter. One obtains the appearance of multiple parameters by passing a tuple as argument. When a function is applied (called), the type of the argument that is passed must be the same as the type of the parameter in the function s definition. The type of the application (call) is the same as the type of the result in the function s definition. In any case where two types A and B must be the same, the ML compiler must unify what it knows about A and B to produce a (potentially more detailed) description of their common type. For example, if the compiler has determined that E1 is an expression of type a * int (that is, a two-element tuple whose second element is known to be an integer), and that E2 is an expression of type string * b, then in the expression if x then E1 else E2, it can infer that a is string and b is int. Thusx is of type bool, and E1 and E2 are of type string * int. Lists As in most functional languages, ML programmers tend to make heavy use of lists. In languages like Lisp and Scheme, which are dynamically typed (and also DESIGN & IMPLEMENTATION Unification Unification is a powerful technique. In addition to its role in type inference (which also arises in the templates [generics] of C++), unification plays a central role in the computational model of Prolog and other logic languages. We will consider this latter role in Section In the general case the cost of unifying the types of two expressions can be exponential [Mai90], but the pathological cases tend not to arise in practice.

4 128 Chapter 7 Data Types EXAMPLE Polymorphic list operators implicitly polymorphic), lists may contain objects of arbitrary types. In ML, all elements of a given list must have the same type, but and this is important functions that manipulate lists without performing operations on their members can take any kind of list as argument: fun append (l1, l2) = if l1 = nil then l2 else hd (l1) :: append (tl (l1), l2); fun member (x, l) = if l = nil then false else if x = hd (l) then true else member (x, tl (l)); EXAMPLE List notation Here append is of type a list * a list -> a list; member is of type a * a list -> bool. The reserved word nil represents the empty list. The built-in :: constructor is analogous to cons in Lisp. It takes an element and a list and tacks the former onto the beginning of the latter; its type is a * a list -> a list. Thehd and tl functions are analogous to car and cdr in Lisp. They return the head and the remainder, respectively, of a list created by ::. Lists are most often written in ML using square bracket notation. The token []is the same as nil. [A,B,C]is the same as A :: B :: C :: nil. Only proper lists those that end with nil can be represented with square brackets. The append function defined above is actually provided in ML as a built-in infix The expression to [a, b, c, d, e, f, g ]. Since ML lists are homogeneous (all elements have the same type), one might wonder about the type of nil. To allow it to take on the type of any list, nil is defined not as an object, but as a built-in polymorphic function of type unit -> a list. The built-in type unit is simply a placeholder, analogous to void in C. A function that takes no arguments is said to have a parameter of type unit. A function that is executed only for its side effects (ML is not purely functional) is said to return a result of type unit. EXAMPLE Resolving ambiguity with explicit types Overloading We have already seen that the equality test (=) is a built-in polymorphic operator. The same is not true of ordering tests (<, <=, >=, >)orarithmetic operators (+, -, *). The equality test can be defined as a polymorphic function because it accepts arguments of any type. The relations and arithmetic operators work only on certain types. To avoid limiting them to a single type of argument (e.g., integers), ML defines them as overloaded names for a collection of built-in functions, each of which operates on objects of a different type (integers, floating-point numbers, strings, etc.). The programmer can define additional such functions for new types. Unfortunately, overloading sometimes interferes with type inference there may not be enough information in an otherwise valid program to resolve which function is named by an overloaded operator:

6 130 Chapter 7 Data Types compare (1, 2, 3); let val t = ("larry", "moe", "curly") in compare (t) end; let val d = (2, 3) in let val (a, b) = d in compare (1, a, b) end end; EXAMPLE Swap in ML EXAMPLE Run-time pattern matching Here pattern matching occurs not only between the parameters and arguments of the call to compare, but also between the left- and right-hand sides of the val construct. (The reserved word val serves to declare a name. The construct fun inc (n) = n+1; is syntactic sugar for val inc = (fn n => n+1);.) As a somewhat more plausible example, we can define a highly useful function that reverses a two-element tuple: fun swap (a, b) = (b, a); Since ML is (mostly) functional, swap is not intended to exchange the value of objects; rather, it takes a two-element tuple as argument, and produces the symmetrical two-element tuple as a result. Pattern matching in ML works not only for tuples, but for any built-in or userdefined constructor of composite values. Constructors include the parentheses used for tuples, the square brackets used for lists, several of the built-in operators etc.), and user-defined constructors of datatypes (see below). Literal constants are even considered to be constructors, so the tuple t can be matched against the pattern (1, x): the match will succeed only if t s first element is 1. In a call like compare (t) or swap (2, 3), an ML implementation can tell at compile time that the pattern match will succeed: it knows all necessary information about the structure of the value being matched against the pattern. In other cases, the implementation can tell that a match is doomed to fail, generally because the types of the pattern and the value cannot be unified. The more interesting cases are those in which the pattern and the value have the same type (i.e., could be unified), but the success of the match cannot be determined until run time. If l is of type int list, for example, then an attempt to deconstruct l into its head and tail may or may not succeed, depending on l s value: let val head :: rest = l in... EXAMPLE ML case expression If l is nil, the attempted match will produce an exception at run time (we will consider exceptions further in Section 8.5). We have seen how pattern matching works in function calls and val constructs. It is also supported by a case expression. Using case, the append function above could have been written as follows: fun append (l1, l2) = case l1 of nil => l2 h :: t => h :: append (t, l2);

7 7.2.4 The ML Type System 131 EXAMPLE Coverage of case labels Here the code generated for the case expression will pattern-match l1 first against nil and then against h::t.thecase expression evaluates to the subexpression following the => in the first arm whose pattern matches. The compiler will issue a warning message at compile time if the patterns of the arms are not exhaustive, or if the pattern in a later arm is completely covered by one in an earlier arm (implying that the latter will never be chosen). A useless arm is probably an error, but harmless, in the sense that it will never result in a dynamic semantic error message. Nonexhaustive cases may be intentional, if the programmer can predict that the pattern will always work at run time. Our append function would have generated such a warning if written as follows: fun append (l1, l2) = if l1 = nil then l2 else let val h::t = l1 in h :: append (t, l2) end; EXAMPLE Function as a series of alternatives EXAMPLE Pattern matching of return tuple Here the compiler is unlikely to realize that the let construct in the else clause will be elaborated only if l1 is nonempty. (This example looks easy enough to figure out, but the general case is uncomputable, and most compilers won t contain special code to recognize easy cases.) When the body of a function consists entirely of a case expression, it can also be written as a simple series of alternatives: fun append (nil, l2) = l2 append (h::t, l2) = h :: append (t, l2); Pattern matching features prominently in other languages as well, particularly those (such as Snobol, Icon, and Perl) that place a heavy emphasis on strings. ML-style pattern matching differs from that of string-oriented languages in its integration with static typing and type inference. Snobol, Icon, and Perl are all dynamically typed. By casting multiargument functions in terms of tuples, ML eliminates the asymmetry between the arguments and return values of functions in many other languages. As shown by swap above, a function can return a tuple just as easily as it can take a tuple argument. Pattern matching allows the elements of the tuple to be extracted by the caller: let val (a, b) = swap (c, d) in... Here a will have the value given by d; b will have the value given by c. Datatype Constructors In addition to lists and tuples, ML provides built-in constructors for records, together with a datatype mechanism that allows the programmer to introduce other kinds of composite types. A record is a composite object in which the elements have names, but no particular order (the language implementation must

8 132 Chapter 7 Data Types EXAMPLE ML records EXAMPLE ML datatypes choose an order for its internal representation, but this order is not visible to the programmer). Records are specified using a curly brace constructor: {name = "Abraham Lincoln", elected = 1860}. (The same value can be denoted {elected = 1860, name = "Abraham Lincoln"}.) ML s datatype mechanism introduces a type name and a collection of constructors for that type. In the simplest case, the constructors are all functions of zero arguments, and the type is essentially an enumeration: datatype weekday = sun mon tue wed thu fri sat; In more complicated examples, the constructors have arguments, and the type is essentially a union (variant record): datatype yearday = mmdd of int * int ddd of int; EXAMPLE Recursive datatypes This code defines mmdd as a constructor that takes a pair of integers as argument, and ddd as a constructor that takes a single integer as argument. The intent is to allow days of the year to be specified either as (month, day) pairs or as integers in the range In a non leap year, the Fourth of July could be represented either as mmdd (7, 4) or as ddd (188), though the equality test mmdd (7, 4) = ddd (188) would fail unless we made yearday an abstract type (similar to the Euclid module types of Section 3.3.4), with its own, special, equality operation. ML s datatypes can even be used to define recursive types, without the need for pointers. The canonical ML example is a binary tree: datatype int_tree = empty node of int * int_tree * int_tree; By introducing an explicit type variable in the definition, we can even create a generic tree whose elements are of any homogeneous type: datatype a tree = empty node of a * a tree * a tree; Given this definition, the tree R X Y Z W EXAMPLE Type equivalence in ML can be written node (#"R", node (#"X", empty, empty), node (#"Y", node (#"Z", empty, empty), node (#"W", empty, empty))). Recursive types also appear in Lisp, Clu, Java, C#, and other languages with a reference model of variables; we will discuss them further in Section 7.7. Because of its use of type inference, ML generally provides the effect of structural type equivalence. Definitions of datatypes can be used to obtain the effect of name equivalence when desired:

9 7.2.4 The ML Type System 133 datatype celsius_temp = ct of int; datatype fahrenheit_temp = ft of int; A value of type celsius_temp can then be obtained by using the ct constructor: val freezing = ct (0); Unfortunately, celsius_temp does not automatically inherit the arithmetic operators and relations of int: unless the programmer defines these operators explicitly, the expression ct (0) < ct (20) will generate an error message along the lines of operator not defined for type. 3CHECK YOUR UNDERSTANDING 54. Under what circumstances does an ML compiler announce a type clash? 55. Explain how the type inference of ML leads naturally to polymorphism. 56. What is a type variable? Give an example in which an ML programmer might use such a variable explicitly. 57. How do lists in ML differ from those of Lisp and Scheme? 58. Why do ML programmers often declare the types of variables, even when they don thaveto? 59. What is unification? What is its role in ML? 60. List three contexts in which ML performs pattern matching. 61. Explain the difference between tuples and records in ML. How does an ML record differ from a record (structure) in languages like C or Pascal? 62. What are ML datatypes? What features do they subsume from imperative languages such as C and Pascal?

10

Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

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

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

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

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

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

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

Type Systems, Type Inference, and Polymorphism

6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

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

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

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

Chapter 15. Functional Programming. Topics. Currying. Currying: example. Currying: example. Reduction

Topics Chapter 15 Functional Programming Reduction and Currying Recursive definitions Local definitions Type Systems Strict typing Polymorphism Classes Booleans Characters Enumerations Tuples Strings 2

CSE 3302 Programming Languages Lecture 8: Functional Programming

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

Products and Records

Products and Records Michael P. Fourman February 2, 2010 1 Simple structured types Tuples Given a value v 1 of type t 1 and a value v 2 of type t 2, we can form a pair, (v 1, v 2 ), containing these values.

Topic 9: Type Checking

Recommended Exercises and Readings Topic 9: Type Checking From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6 and

Topic 9: Type Checking

Topic 9: Type Checking 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6

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

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

CS558 Programming Languages

CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

CS558 Programming Languages

CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

Chapter 3 Linear Structures: Lists

Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9

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,

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference

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

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

Chapter 3 Linear Structures: Lists

Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:

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

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

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

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

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

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

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

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 The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

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

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

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

A Fourth Look At ML Chapter Eleven Modern Programming Languages, 2nd ed. 1 Type Definitions Predefined, but not primitive in ML: datatype bool = true false; Type constructor for lists: datatype 'element

(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

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

This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator

1 2 This example highlights the difference between imperative and functional programming. The imperative programming solution is based on an accumulator (total) and a counter (i); it works by assigning

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

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

ICOM 4036 Programming Languages Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference Types Data Types This

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 The ML Programming Language General purpose programming language designed by Robin Milner in 1970 Meta Language

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

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

Types and Programming Languages. Lecture 5. Extensions of simple types

Types and Programming Languages Lecture 5. Extensions of simple types Xiaojuan Cai cxj@sjtu.edu.cn BASICS Lab, Shanghai Jiao Tong University Fall, 2016 Coming soon Simply typed λ-calculus has enough structure

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

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

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

Modern 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

Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Every program uses data, either explicitly or implicitly to arrive at a result. Data in a program is collected into data structures, and is manipulated by algorithms. Algorithms + Data Structures = Programs

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

CMSC 331 Final Exam Section 0201 December 18, 2000

CMSC 331 Final Exam Section 0201 December 18, 2000 Name: Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for

Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

Some instance messages and methods

Some instance messages and methods x ^x y ^y movedx: dx Dy: dy x

Mini-ML. CS 502 Lecture 2 8/28/08

Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of

Typed 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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

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

RSL Reference Manual

RSL Reference Manual Part No.: Date: April 6, 1990 Original Authors: Klaus Havelund, Anne Haxthausen Copyright c 1990 Computer Resources International A/S This document is issued on a restricted basis

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compile-time Static 1. Enter expression 2. ML infers a type Exec-time Dynamic Types 3. ML crunches expression down to a value 4. Value

Static Checking and Type Systems

1 Static Checking and Type Systems Chapter 6 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2009 2 The Structure of our Compiler Revisited Character stream Lexical

Introduction to Programming, Aug-Dec 2006

Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components

Intermediate 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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

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

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

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

CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell: Declaring Types and Classes Dr. Hyunyoung Lee 1 Outline Declaring Data Types Class and Instance Declarations 2 Defining New Types Three constructs for defining types:

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

CSE 401 Compilers Static Semantics Hal Perkins Winter 2009 2/3/2009 2002-09 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Symbol tables General ideas for now; details later for MiniJava project

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

A Small Interpreted Language

A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

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

1 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

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

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,

Functional programming with Common Lisp

Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

The 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

The type checker will complain that the two branches have different types, one is string and the other is int

1 Intro to ML 1.1 Basic types Need ; after expression - 42 = ; val it = 42 : int - 7+1; val it = 8 : int Can reference it - it+2; val it = 10 : int - if it > 100 then "big" else "small"; val it = "small"

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

CSE 130 : Fall 2007 Programming Languages News PA deadlines shifted PA #2 now due 10/24 (next Wed) Lecture 5: Functions and Datatypes Ranjit Jhala UC San Diego Recap: Environments Phone book Variables

Introduction to OCaml

Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

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,

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

Programming Languages

CSE 130 : Winter 2009 Programming Languages News PA 2 out, and due Mon 1/26 5pm Lecture 5: Functions and Datatypes t UC San Diego Recap: Environments Phone book Variables = names Values = phone number

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

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

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations