Lambda Calculus and Type Inference

Similar documents
Lambda Calculus and Type Inference

(Refer Slide Time: 4:00)

Chapter 5: The Untyped Lambda Calculus

More Untyped Lambda Calculus & Simply Typed Lambda Calculus

The Untyped Lambda Calculus

CS 242. Fundamentals. Reading: See last slide

Functional Programming

5. Introduction to the Lambda Calculus. Oscar Nierstrasz

Last class. CS Principles of Programming Languages. Introduction. Outline

Pure Lambda Calculus. Lecture 17

Lambda Calculus. Variables and Functions. cs3723 1

Type Systems COMP 311 Rice University Houston, Texas

List Functions, and Higher-Order Functions

What does my program mean?

Formal Systems and their Applications

From the λ-calculus to Functional Programming Drew McDermott Posted

λ calculus Function application Untyped λ-calculus - Basic Idea Terms, Variables, Syntax β reduction Advanced Formal Methods

Introduction to the Lambda Calculus

The Untyped Lambda Calculus

COMP80 Lambda Calculus Programming Languages Slides Courtesy of Prof. Sam Guyer Tufts University Computer Science History Big ideas Examples:

Critical Analysis of Computer Science Methodology: Theory

CSE 3302 Programming Languages Lecture 8: Functional Programming

9/23/2014. Why study? Lambda calculus. Church Rosser theorem Completeness of Lambda Calculus: Turing Complete

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

Programming Language Features. CMSC 330: Organization of Programming Languages. Turing Completeness. Turing Machine.

CMSC 330: Organization of Programming Languages

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

Lambda Calculus: Implementation Techniques and a Proof. COS 441 Slides 15

Untyped Lambda Calculus

One of a number of approaches to a mathematical challenge at the time (1930): Constructibility

Types and Type Inference

1 Scope, Bound and Free Occurrences, Closed Terms

Lambda Calculus. Concepts in Programming Languages Recitation 6:

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Functional Programming

Fall 2013 Midterm Exam 10/22/13. This is a closed-book, closed-notes exam. Problem Points Score. Various definitions are provided in the exam.

(Refer Slide Time: 01:01)

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Programming Languages Lecture 14: Sum, Product, Recursive Types

Type Processing by Constraint Reasoning

CMSC 330: Organization of Programming Languages

Untyped Lambda Calculus

Costly software bugs that could have been averted with type checking

Exercise 1 ( = 24 points)

Lambda Calculus. Type Systems, Lectures 3. Jevgeni Kabanov Tartu,

Lambda Calculus. Lecture 4 CS /26/10

Type Systems, Type Inference, and Polymorphism

The Untyped Lambda Calculus

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

λ calculus is inconsistent

Types and Type Inference

Type Checking and Type Inference

Introduction to the Lambda Calculus. Chris Lomont

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

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

Programming Languages Fall 2014

Problem Solving, Programming, and Calculation

Exercise 1 ( = 22 points)

Functional Languages and Higher-Order Functions

Lecture #23: Conversion and Type Inference

Lambda calculus. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 6

Chapter 5: The Untyped Lambda Calculus

CSCI-GA Scripting Languages

Foundations. Yu Zhang. Acknowledgement: modified from Stanford CS242

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

M. Snyder, George Mason University LAMBDA CALCULUS. (untyped)

Arbitrary-rank polymorphism in (GHC) Haskell

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages. Lambda calculus

Programming Language Concepts: Lecture 14

dynamically typed dynamically scoped

Chapter 2 The Language PCF

Programming Languages Third Edition

CMSC 336: Type Systems for Programming Languages Lecture 5: Simply Typed Lambda Calculus Acar & Ahmed January 24, 2008

Formal Semantics. Aspects to formalize. Lambda calculus. Approach

Polymorphism and Type Inference

Functional Languages. Hwansoo Han

Pure (Untyped) λ-calculus. Andrey Kruglyak, 2010

Programming Languages

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

Type Systems Winter Semester 2006

Com S 541. Programming Languages I

Exercise 1 ( = 18 points)

Functional Programming. Overview. Topics. Recall λ-terms. Examples

J. Barkley Rosser, 81, a professor emeritus of mathematics and computer science at the University of Wisconsin who had served in government, died

Lesson 4 Typed Arithmetic Typed Lambda Calculus

Lecture 19: Functions, Types and Data Structures in Haskell

Polymorphic Types in ACL2

CSE-321 Programming Languages 2011 Final

Lambda Calculus.

Programming Languages

1.3. Conditional expressions To express case distinctions like

Recursive Definitions, Fixed Points and the Combinator

COMP 4161 NICTA Advanced Course. Advanced Topics in Software Verification. Toby Murray, June Andronick, Gerwin Klein

Functional Logic Programming. Kristjan Vedel

Simple Unification-based Type Inference for GADTs

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

Typed Lambda Calculus for Syntacticians

Symmetry in Type Theory

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

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Transcription:

Lambda Calculus and Type Inference Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ October 13, 2004 Lambda Calculus and Type Inference (revised 2004-10-12)

The Topics Lambda Calculus: a formal calculus for functions and how to compute with them Type Inference: how to find the possible type(s) of expressions, without explicit typing Lambda Calculus and Type Inference (revised 2004-10-12) 1

Lambda Calculus Formal calculus Invented by logicians around 1930 Formal syntax for functions, and function application Gives a certain computational meaning to function application Theorems about reduction order (which possible subcomputation to execute first) This is related to call-by-value/call-by-need Several variations of the calculus Lambda Calculus and Type Inference (revised 2004-10-12) 2

ffl an application e 1 e 2 The Simple Untyped Lambda Calculus A term in this calculus is: a variable x, ffl a lambda-abstraction x:e, or ffl Some examples: x x y x x x:(x y) ( x:x) y x: y: x:x Any term can be applied to any term, no concept of (function) types Syntax: function application binds strongest, x:x y = x:(x y) 6= ( x:x) y Lambda Calculus and Type Inference (revised 2004-10-12) 3

Untyped Lambda Calculus with Constants We can extend the syntax with constants, for instance: 1, 17, +, [], : We can then write terms closer to Haskell, like 17 + x x:(x + y) l: x:(l : x) Every Haskell program can be translated into an intermediate form, which essentially is a lambda calculus with constants Some constants (like +) can be given a computational meaning, more on this later Lambda Calculus and Type Inference (revised 2004-10-12) 4

Equivalences Some lambda-expressions are considered equivalent (e 1 e 2 ) Rule 1: change of name of bound variable gives an equivalent expression (alpha-conversion) So x:(x x) y:(y y) Quite natural, right? However, beware of variable capture: x: y:x 6 y: y:y Renaming must avoid name clashes with locally bound variables Note that ( x: y:x) 17 = y:17, whereas ( y: y:y) 17 = y:y. Different! Lambda Calculus and Type Inference (revised 2004-10-12) 5

( x: y:(x + y)) y ( x: z:(x + z)) y! fi z:(y + z) Beta-reduction A lambda abstraction applied to an expression can be beta-reduced: ( x:x + x) 9! fi 9 + 9 Beta-reduction means substitute actual argument for symbolic parameter in function body Works also with symbolic arguments: + x) ( x:y z)! fi ( x:y z) + ( x:y z) ( x:x However, beware of variable capture: ( x: y:(x + y)) y 6! fi y:(y + y) The fix is to first rename the bound variable y: Lambda Calculus and Type Inference (revised 2004-10-12) 6

Extending the Equivalence We consider expressions equal if there is a way to convert them into each other, through beta-reductions or inverse beta-reductions For instance, ( x:x) 17 ( y:17) z since ( x:x) 17! fi 17 ψ fi ( y:17) z Lambda Calculus and Type Inference (revised 2004-10-12) 7

Some Encodings Many mathematical concepts can be encoded in the lambda-calculus That is, they can be translated into the calculus For instance, we can encode the boolean constants, and a conditional (functional if-then-else): T RUE = x: y:x F ALSE = x: y:y C OND = p: q: r:(p q r) Lambda Calculus and Type Inference (revised 2004-10-12) 8

An example of how C OND works: C OND T RUE A B! fi ( p: q: r:(p q r)) ( x: y:x) A B! fi ( q: r:(( x: y:x) q r)) A B! fi ( r:(( x: y:x) A r)) B! fi ( x: y:x) A B! fi y:a B! fi A Try evaluating C OND F ALSE A B yourself! Lambda Calculus and Type Inference (revised 2004-10-12) 9

Boolean connectives (and, or) can also be encoded As well as lists, integers, ::: Actually anything you can do in a functional language! Lambda Calculus and Type Inference (revised 2004-10-12) 10

Nontermination Consider this expression: ( x:x x) ( x:x x) What if we beta-reduce it? ( x:x x) ( x:x x)! fi ( x:x x) ( x:x x) Whoa, we got back the same! Scary ::: Clearly, we can reduce ad infinitum The lambda-calculus thus contains nonterminating reductions Lambda Calculus and Type Inference (revised 2004-10-12) 11

! fi ( x:f (x x)) ( x:f (x x))! fi f (( x:f (x x)) ( x:f (x x))) Recursion Now consider this expression: h:( x:h (x x)) ( x:h (x x)) Let s call it Y What if we apply it to a function f? Y f = h:( x:h (x x)) ( x:h (x x)) f = f (Y f ) Hmm, we got back f applied to Y f Lambda Calculus and Type Inference (revised 2004-10-12) 12

is called fixed-point combinator Y It encodes recursion To see why, consider the recursive definition x = f x The solution is = f f f x Likewise, f = f (Y f ) = f f (Y f ) = f f f Y x = Y Thus, f! Note that all recursive definitions can be written on the form x = f x Lambda Calculus and Type Inference (revised 2004-10-12) 13

Reduction Strategies Any application of a lambda-abstraction in an expression can be beta-reduced Each such position is called a redex An expression can contain several redexes Can you find all redexes in this expression? ( x:(( y:y) x) (( y:y) x) Try reduce them in different orders! Lambda Calculus and Type Inference (revised 2004-10-12) 14

Does the order of reducing redexes matter? Well, yes and no: Theorem: if two different reduction orders of the same expression end in expressions that cannot be further reduced, then these expressions must be the same However, we can have potentially infinite reductions: ( x:y) (( x:x x) ( x:x x)) Reducing the outermost redex yields y But the innermost redex can be reduced infinitely many times nontermination! So the order does matter, as regards termination anyway! Lambda Calculus and Type Inference (revised 2004-10-12) 15

Normal Order Reduction Consider this slight adaptation of the previous example: ( x:x) (( x:x x) ( x:x x)) ( x: x:y) Let us draw it as a tree: @ @ @ \x > \x > y \x > x \x > x x \x > x x Reducing the leftmost-outermost redex twice yields y Lambda Calculus and Type Inference (revised 2004-10-12) 16

Some other reduction orders do not terminate This is not a coincidence! To reduce the leftmost-outermost redex in each step is called normal order reduction Theorem: if there is a reduction order that terminates, then normal order reduction terminates Normal order reduction corresponds to call-by-need in functional languages Lambda Calculus and Type Inference (revised 2004-10-12) 17

Type Inference You have seen that Haskell systems can find types for expressions: y f = f (y f) y :: a -> a -> a As we have mentioned, the most general type is always found Lambda Calculus and Type Inference (revised 2004-10-12) 18

There is an interesting theory behind Haskell-style type inference To infer means to prove, or to deduce A type system is a logic, whose statements are of form expression e has type fi To infer a type means to prove a statement like above A type inference algorithm finds a type if it exists: it is thus a proof search algorithm Such an algorithm exists for Haskell s type system Lambda Calculus and Type Inference (revised 2004-10-12) 19

Hindley-Milner s Type System Haskell s type system extends a simpler type system known as Hindley-Milner s type system (HM) HM does not have type classes, and it is defined over a simple lambda-calculus language Here, we will briefly describe a subset of HM: Language is lambda-calculus with constants (also known functions, like +) Constants have typing given in advance Recursion can be encoded through constant Y (fixed-point combinator) Lambda Calculus and Type Inference (revised 2004-10-12) 20

A language of types: ffl type constants (like I nt) ffl type variables ff ffl function types fi! fi 0 (! is a type constructor) ffl type schemes 8ff:fi Other type constructors (for list types etc) can easily be added Type schemes like 8ff:ff! ff correspond to polymorphic Haskell types like a -> a Lambda Calculus and Type Inference (revised 2004-10-12) 21

Statements Statements of form A ` e : fi, where e is expression and fi is a type A is a set of assumptions, of form x : fi (read: variable x has type fi ) ` e : fi is read under the assumptions on typings of variables in A, the A e expression can have type fi So in order to prove such a statement, we must guess some typings of variables in e and then check that we can give e a consistent type with these assumptions The key in type inference is to make these guesses systematically Lambda Calculus and Type Inference (revised 2004-10-12) 22

Inference Rules Axioms and allowed proof steps are given as a set of inference rules Each inference rule has a number of premises and a conclusion Often written on the form premise 1 n premise conclusion Example (modus ponens in propositional logic): P =) Q P Q Axioms are inference rules without premises Lambda Calculus and Type Inference (revised 2004-10-12) 23

[ fx : ffg ` e : fi A ` x:e : ff! fi A Hindley-Milner Inference Rules A selection of rules from the HM inference system: A [ fx : fig ` x : fi [V AR] [ABS] ` e : ff! fi A ` e 0 : ff A ` e e 0 : fi A [APP] ` e : 8ff:fi A ` e : fi [ff=ff] A [SPEC] (fi [ff=ff] stands for fi with ff replacing every occurrence of ff) Lambda Calculus and Type Inference (revised 2004-10-12) 24

An Example Best way to understand inference rules is to see a derivation Let s infer a type ( y:(tail y)) nil for Extend language of types with list [fi ] types Assume given typings for constants: A = fnil : 8ff:[ff]; tail : 8ff:[ff]! [ff]g Lambda Calculus and Type Inference (revised 2004-10-12) 25

T = A ` ( y:(tail y)) nil : [fl] A [ fy : [fl]g ` tail y : [fl] ` nil : 8ff:[ff] A ` nil : [fl] A A [ fy : [fl]g ` y : [fl] Derivation T ` y:(tail y) : [fl]! [fl] A where [ fy : [fl]g ` tail : 8ff:[ff]! [ff] A [ fy : [fl]g ` tail : [fl]! [fl] A Lambda Calculus and Type Inference (revised 2004-10-12) 26

Inference Algorithm There is a classical algorithm for type inference in the HM system Called algorithm W Basically a systematic and efficient way to infer types like we did in the example The algorithm uses unification, remember this when you learn logic programming! It has been proved that algorithm W always yields a most general type for any typable expression Most general means that any other possible type for the expression can be obtained from the most general type by instantiating its type variables Lambda Calculus and Type Inference (revised 2004-10-12) 27

A More Practical Type Inference Example Define length [] = 0 length (x:xs) = 1 + length xs Derive the most general type for length! For simplicity, assume that 0 :: Int, 1 :: Int, and (+) :: Int -> Int -> Int See next four slides for how to do it ::: Lambda Calculus and Type Inference (revised 2004-10-12) 28

Type inference can be seen as equation solving: every declaration gives rise to a type equation constraining the types for the untyped identifiers These equations can be solved to find the types In our example, we already know: 0 :: Int 1 :: Int (+) :: Int -> Int -> Int [] :: [a] (:) :: b -> [b] -> [b] Note different type variable names in types of [] and (:), to make sure they re not mixed up Lambda Calculus and Type Inference (revised 2004-10-12) 29

Solving the equation for the first declaration: length [] = 0 length :: c -> d (since it is applied to one argument) c = [a] (from what we know about the type of []) d = Int (since length [] :: d, 0 :: Int, and both sides of the declaration must have the same type) Thus, length :: [a] -> Int Is this consistent with the second case in declaration of length? Lambda Calculus and Type Inference (revised 2004-10-12) 30

Second declaration length (x:xs) = 1 + length xs Must first find possible types for x, xs, x:xs Assume x :: e, xs :: f e = b, f = [b] (or else x:xs is not well-typed), then x:xs :: [b] Left-hand side: OK if [b] = [a] (so xs :: [a] and x:xs :: [a]), and then length (x:xs) :: Int Right-hand side: xs :: [b], length :: [a] -> Int and xs :: [a] gives length xs :: Int 1 :: Int, length xs :: Int, (+) :: Int -> Int -> Int gives 1 + length xs :: Int Lambda Calculus and Type Inference (revised 2004-10-12) 31

Thus type of LHS = type of RHS! We re done. Result: length :: [a] -> Int Must be a most general type since we were careful not to make any stronger assumptions than necessary about any types (In the formal type system, we would obtain length : 8ff:[ff]! Int) Lambda Calculus and Type Inference (revised 2004-10-12) 32

Applications of Type Inference HM-style type systems used in some advanced functional languages, most notably ML and Haskell Similar type inference systems can be used for program analysis Types (not the usual ones) can stand for properties e : fi then means expression (program) e has property fi Can be used in optimizing compilers Another application: dimensional analysis, to find whether equations are sound w.r.t. physical dimensions Lambda Calculus and Type Inference (revised 2004-10-12) 33