301AA - Advanced Programming [AP-2017]

Similar documents
Principles of Programming Languages

301AA - Advanced Programming

Principles of Programming Languages

301AA - Advanced Programming [AP-2017]

Chapter 11 :: Functional Languages

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

Programming Language Pragmatics

Functional Languages. Hwansoo Han

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

Introduction to Haskell

Introduction to ML. Based on materials by Vitaly Shmatikov. General-purpose, non-c-like, non-oo language. Related languages: Haskell, Ocaml, F#,

CIS 500 Software Foundations Fall September 25

Recursion. Lecture 6: More Lambda Calculus Programming. Fixed Points. Recursion

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Programming Languages Fall 2013

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

301AA - Advanced Programming [AP-2017]

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Type Systems Winter Semester 2006

Introduction to Haskell

An introduction introduction to functional functional programming programming using usin Haskell

10/21/08. Kathleen Fisher! Question:! Interesting answer in Algol:!

Imperative languages

Lecture 9: More Lambda Calculus / Types

- M ::= v (M M) λv. M - Impure versions add constants, but not necessary! - Turing-complete. - true = λ u. λ v. u. - false = λ u. λ v.

Chapter 5: The Untyped Lambda Calculus

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

Functional Programming

Functional Programming

The Lambda Calculus. 27 September. Fall Software Foundations CIS 500. The lambda-calculus. Announcements

Functional Languages and Higher-Order Functions

9/28/09. Kathleen Fisher. Question: Interesting answer in Algol:

LECTURE 16. Functional Programming

301AA - Advanced Programming

4/13/15. Kathleen Fisher for cs242 at Tufts Lightly edited with permission, Michelle Strout 4/10/15

Language Sequence. The Algol Family and ML. Algol 60 Sample. Algol 60. Some trouble spots in Algol 60. Algol Joke. John Mitchell

CS 11 Haskell track: lecture 1

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

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.

CSCI-GA Scripting Languages

Graphical Untyped Lambda Calculus Interactive Interpreter

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

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Haskell An Introduction

Programming with Math and Logic

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Functional Programming and λ Calculus. Amey Karkare Dept of CSE, IIT Kanpur

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

Lecture 19: Functions, Types and Data Structures in Haskell

Principles of Programming Languages

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

CSE 3302 Programming Languages Lecture 8: Functional Programming

Functional Programming. Pure Functional Programming

Types and Type Inference

λ-calculus Lecture 1 Venanzio Capretta MGS Nottingham

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

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

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

Introduction to OCaml

Introduction. chapter Functions

An introduction to functional programming. July 23, 2010

Introduction to Lambda Calculus. Lecture 5 CS 565 1/24/08

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

5. Introduction to the Lambda Calculus. Oscar Nierstrasz

Exercise 1 ( = 24 points)

11/6/17. Outline. FP Foundations, Scheme. Imperative Languages. Functional Programming. Mathematical Foundations. Mathematical Foundations

Lecture #23: Conversion and Type Inference

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

CS 4110 Programming Languages & Logics. Lecture 17 Programming in the λ-calculus

CSCE 314 Programming Languages

Introduction to Lambda Calculus. Lecture 7 CS /08/09

Functional Programming

Haskell Overview II (2A) Young Won Lim 8/9/16

Organization of Programming Languages CS3200/5200N. Lecture 11

CITS3211 FUNCTIONAL PROGRAMMING. 10. Programming in the pure λ calculus

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

Recursive Definitions, Fixed Points and the Combinator

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Formal Semantics. Aspects to formalize. Lambda calculus. Approach

Denotational Semantics. Domain Theory

Functional Programming and Haskell

Logic - CM0845 Introduction to Haskell

Announcements. CSCI 334: Principles of Programming Languages. Lecture 5: Fundamentals III & ML

Pure Lambda Calculus. Lecture 17

Formal Systems and their Applications

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

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Haskell 5.1 INTERACTIVE SESSIONS AND THE RUN-TIME SYSTEM

Functional Programming. Big Picture. Design of Programming Languages

Exercise 1 ( = 22 points)

CMSC 330: Organization of Programming Languages

Introduction to Haskell

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

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

CS 320: Concepts of Programming Languages

COMP 1130 Lambda Calculus. based on slides by Jeff Foster, U Maryland

Costly software bugs that could have been averted with type checking

CS 457/557: Functional Languages

Transcription:

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-15: Func'onal Programming

FuncLonal Programming: Historical Origins The imperalve and funclonal models grew out of work undertaken Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s different formalizalons of the nolon of an algorithm, or effec,ve procedure, based on automata, symbolic manipulalon, recursive funclon definilons, and combinatorics These results led Church to conjecture that any intuilvely appealing model of compulng would be equally powerful as well this conjecture is known as Church s thesis 2

Historical Origins Church s model of compulng is called the lambda calculus based on the nolon of parameterized expressions (parameter introduced leber λ, hence the notalon s name) allows one to define mathemalcal funclons in a construclve/effeclve way lambda calculus was the inspiralon for funclonal programming computalon proceeds by subsltulng parameters into expressions, just as one computes in a high level funclonal program by passing arguments to funclons We shall see later the basic of lambda-calculus 3

FuncLonal Programming Concepts FuncLonal languages such as Lisp, Scheme, FP, ML, Miranda, and Haskell are an abempt to realize Church s lambda calculus in praclcal form as a programming language The key idea: do everything by composing funclons no mutable state no side effects 4

FuncLonal Programming Concepts Necessary features, many of which are missing in some imperalve languages: 1st class and high-order funclons recursion Takes the place of iteralon powerful list facililes Recursive funclon exploit recursive definilon of lists Polymorphism (typically universal parametric implicit) Relevance of Container/CollecLons fully general aggregates Data structures cannot be modified, have to be re-created structured funclon returns garbage colleclon Unlimited extent for locally allocated data structures 5

Other Related Concepts Lisp also has some features that are not necessary present in other funclonal languages: programs are data self-definilon read-evaluate-print interaclve loop Variants of LISP (Original) Lisp: purely funclonal, dynamically scoped Common Lisp: current standard, stalcally scoped, very complex Scheme: stalcally scoped, very elegant, used for teaching 6

Other funclonal languages: the ML family Robin Milner (Turing award in 1991, CCS, Pi-calculus, ) StaLcally typed, general-purpose programming language Meta-Language of the LCF theorem proving system Type safe, with type inference and formal semanlcs Compiled language, but intended for interaclve use CombinaLon of Lisp and Algol-like features Expression-oriented Higher-order funclons Garbage colleclon Abstract data types Module system ExcepLons 7

Other funclonal languages: Haskell Designed by commibee in 80 s and 90 s to unify research efforts in lazy languages EvoluLon of Miranda Haskell 1.0 in 1990, Haskell 98, Haskell 2010 Several features in common with ML, but some differ: Types and type checking Type inference Implicit parametric polymorphism Ad hoc polymorphism (overloading) Control Lazy vs. eager evalua@on Tail recursion and conlnualons Purely funclonal Precise management of effects 8

Downloading Haskell hbps://www.haskell.org/plaoorm/ 9

Core Haskell Basic Types Unit Booleans Integers Strings Reals Tuples Lists Records PaBerns DeclaraLons FuncLons Polymorphism Type declaralons Type Classes Monads ExcepLons 10

Overview of Haskell InteracLve Interpreter (ghci): read-eval-print ghci infers type before compiling or execulng Type system does not allow casts or similar things! Examples Prelude> 5==4 False Prelude> :set +t -- enables printing of types Prelude> 'x' 'x' it :: Char Prelude> (5+3)-2 6 it :: Num a => a --?? generic constrained type Prelude> :t map -- type of a function map :: (a -> b) -> [a] -> [b] 11

Booleans Overview by Type True, False :: Bool not :: Bool -> Bool and, or :: Foldable t => t Bool -> Bool if then else --types must match Characters & Strings 'a','b',';','\t', '2', 'X' :: Char "Ron Weasley" :: [Char] --strings are lists of chars 12

Numbers Overview by Type 0,1,2, :: Num p => p --type classes to disambiguate 1.0, 3.1415 :: Fractional a => a -> a -> a (45 :: Integer) :: Integer -- explicit typing +, *, -, :: Num a => a -> a -> a -- infix + becomes prefix (+) -- prefix binary op becomes infix `op` / :: Fractional a => a -> a -> a div, mod :: Integral a => a -> a -> a ^ :: (Num a, Integral b) => a -> b -> a 13

Simple Compound Types Tuples ("AP",2017) :: Num b => ([Char], b) -- pair fst :: (a, b) -> a snd :: (a, b) -> b ('4', True, "PLP") :: (Char, Bool, [Char]) Lists [] :: [a] -- NIL, polymorphic type 1 : [2, 3, 4] :: [Integer] -- infix cons notation [1,2]++[3,4] :: [Integer] -- concatenation Records data Person = Person {firstname :: String, lastname :: String} hg = Person { firstname = "Hermione", lastname = "Granger"} 14

More on list constructors ghci> [1..20] -- ranges [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] ghci> ['a'..'z'] "abcdefghijklmnopqrstuvwxyz" ghci> [3,6..20] -- ranges with step [3,6,9,12,15,18] ghci> [7,6..1] [7,6,5,4,3,2,1] ghci> [1..] -- an infinite list: runs forever ghci> take 10 [1..] -- prefix of an infinite lists [1,2,3,4,5,6,7,8,9,10] -- returns! ghci> take 10 (cycle [1,2]) [1,2,1,2,1,2,1,2,1,2] ghci> take 10 (repeat 5) [5,5,5,5,5,5,5,5,5,5] How does it work??? Later 15

PaBerns and DeclaraLons PaBerns can be used in place of variables <pat> ::= <var> <tuple> <cons> <record> Value declaralons General form: <pat> = <exp> Examples mytuple = ("Foo", "Bar") (x,y) = mytuple -- x = "Foo, y = "Bar" mylist = [1, 2, 3, 4] z:zs = mylist -- z = 1, zs = [2,3,4] Local declaralons let (x,y) = (2, "FooBar") in x * 4 16

Anonymous FuncLons (lambda abstraclon) Anonymous funclons \x -> x+1 --like Lisp lambda, function ( ) in JS (\x -> x+1)5 => 6 f = \x -> x+1 f 7 => 8 Anonymous funclons using paberns Prelude> h = \(x,y) -> x+y h :: Num a => (a, a) -> a Prelude> h (3, 4) => 7 Prelude> h 3 4 => error Prelude> k = \(z:zs) -> length zs k :: [a] -> Int Prelude> k "hello => 4 17

FuncLon declaralons FuncLon declaralon form <name> <pat 1 > = <exp 1 > <name> <pat 2 > = <exp 2 > Examples f (x,y) = x+y --argument must match pattern (x,y) length [] = 0 length (x:s) = 1 + length(s) 18

More FuncLons on Lists Apply funclon to every element of list map f [] = [] map f (x:xs) = f x : map f xs map (\x -> x+1) [1,2,3] [2,3,4] Reverse a list reverse [] = [] -- quadratic reverse (x:xs) = (reverse xs) ++ [x] reverse xs = -- linear, tail recursive let rev ( [], accum ) = accum rev ( y:ys, accum ) = rev ( ys, y:accum ) in rev ( xs, [] ) 19

On laziness Haskell is a lazy language FuncLons and data constructors don t evaluate their arguments unll they need them In several languages there are forms of lazy evalualons (if-then-else, shortcuwng && and )! if (x!= 0) return y/x; else return 0; //ok! if (x!=0 && y/x > 5) return 0; else return 1; //ok! if (x!=0 & y/x > 5) return 0; else return 1; //no!! int choose(boolean e1, boolean e2){! if (e1 && e2) return 0; else return 1;! }! choose(x!=0, y/x>5) //???! Ok in Haskell, thanks to Normal Order evalua@on and Call by Need parameter passing 20

A digression on λ-calculus 21

λ-calculus: syntax λ-terms: t ::= x λx.t t t (t) x variable, name, symbol, λx.t abstrac'on, defines an anonymous funclon t t' applica'on of funclon t to argument t Terms can be represented as abstract syntax trees SyntacLc ConvenLons ApplicaLons associates to lez t 1 t 2 t 3 (t 1 t 2 ) t 3 The body of abstraclon extends as far as possible λx. λy. x y x λx. (λy. (x y) x) A simple tutorial on lambda calculus: http://www.inf.fu-berlin.de/lehre/ws03/alpi/lambda.pdf! 22

Free vs. Bound Variables An occurrence of x is free in a term t if it is not in the body of an abstraclon λx. t otherwise it is bound λx is a binder Examples λz. λx. λy. x (y z) (λx. x) x Terms without free variables are combinators IdenLty funclon: id = λx. x First projeclon: fst = λx. λy. x

OperaLonal SemanLcs [β-reduclon] func'on applica'on redex (λx.t) t' = t [t'/x] (λ x. x) y (λ x. x (λ x. x) ) (u r) y u r (λ x.x) (λ x (λw. x w)) (y z) λw. y z w

λ-calculus as a funclonal language Despite the simplicity, we can encode in λ- calculus most concepts of funclonal languages: FucLons with several arguments Booleans and logical conneclves Integers and operalons on them Pairs and tuples 25

FuncLons with several arguments A definilon of a funclon with a single argument associates a name with a λ-abstraclon f x = <exp> f = λx.<exp> -- is equivalent to A funclon with several argument is equivalent to a sequence of λ-abstraclons f(x,y) = <exp> -- is equivalent to f = λx.λy.<exp> Currying and Uncurrying curry :: ((a, b) -> c) -> a -> b -> c uncurry :: (a -> b -> c) -> (a, b) -> c

Church Booleans T = λt.λf.t -- first! F = λt.λf.f -- second! and = λb.λc.bcf! or = λb.λc.btc! not = λx.xft! test =λl.λm.λn.lmn! test F u w! à (λl.λm.λn.lmn) F u w! à (λm.λn.fmn) u w! à (λn.fun) w! à Fuw! à w! and T F! à (λb.λc.bcf) T F! à (λc.tcf) F! à TFF! à F! not F! à (λx.xft) F! à FFT! à T!

Pairs pair = λf.λs.λb.b f s! fst = λp.p T! snd = λp.p F! fst (pair u w)! à (λp.p T) (pair u w)! à (pair u w) T! à (λf.λs.λb.b f s) u w T! à (λs.λb.b u s) w T! à (λb.b u w) T! à T u w! à u!

Numerals c 0 = λs. λz. z! c 1 = λs. λz. s z! c 2 = λs. λz. s (s z)! c 3 = λs. λz. s (s (s z))! succ = λn. λs. λz. s (n s z)! plus = λm. λn. λs. λz. m s (n s z)! times = λm. λn. m (plus n) c 0! Turing Complete! succ c2! à (λn. λs. λz. s (n s z)) c2! à (λs. λz. s (c2 s z))! à (λs. λz. s ((λs. λz. s (s z)) s z))! à (λs. λz. s (s (s z)) = c3!