CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.

Slides:



Advertisements
Similar presentations
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
Advertisements

A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
Cs776 (Prasad)L4Poly1 Polymorphic Type System. cs776 (Prasad)L4Poly2 Goals Allow expression of “for all types T” fun I x = x I : ’a -> ’a Allow expression.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
CSE 3341/655; Part 4 55 A functional program: Collection of functions A function just computes and returns a value No side-effects In fact: No program.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function F can return.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Patterns in ML functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are the.
ML Exceptions.1 Standard ML Exceptions. ML Exceptions.2 Exceptions – The Need  An extensive part of the code is error handling  A function can return.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Introduction to ML You will be responsible for learning ML on your own. Today I will cover some basics Read Robert Harper’s notes on “an introduction to.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
Functional Programming Professor Yihjia Tsai Tamkang University.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Introduction and Chapter 8 of Programming Languages by Ravi Sethi Elements of Functional Programming.
Functional Programming Element of Functional Programming.
PrasadCS7761 Haskell Data Types/ADT/Modules Type/Class Hierarchy Lazy Functional Language.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Chapter 9: Functional Programming in a Typed Language.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
CS5205Haskell1 CS5205: Foundations in Programming Languages FP with Haskell A pure lazy functional language that embodies many innovative ideas in language.
TIVDM2Functional Programming Language Concepts 1 Concepts from Functional Programming Languages Peter Gorm Larsen.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
An introduction to functional programming using Haskell CENG242 –Recitation 1.
CSE-321 Programming Languages Introduction to Functional Programming POSTECH March 8, 2006 박성우.
Functional Programming
Functional Programming
String is a synonym for the type [Char].
Conditional Expressions
Functional Programming
Principles of programming languages 12: Functional programming
Types CSCE 314 Spring 2016.
ML: a quasi-functional language with strong typing
A lightening tour in 45 minutes
PROGRAMMING IN HASKELL
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
FP Foundations, Scheme In Text: Chapter 14.
Functional Programming
PROGRAMMING IN HASKELL
CSE 341 Section 5 Winter 2018.
CSE-321 Programming Languages Introduction to Functional Programming
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
CSE-321 Programming Languages Introduction to Functional Programming
Presentation transcript:

CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes

reduce (op *) [2,4,6] 1 ==> 2 * (4 * (6 * 1)) ==> 48 reduce (fn (x,y)=>1+y) [2,4,6] 0 ==> 1 + (1 + (1 + 0)) ==> 3 [] : 2: 4:

Types: Classification of Values and Their Operators TypeValuesOperations booltrue,false=, <>, … int…,~1,0,1,2,…=,<>,<,+,div,… real..,0.0,.,3.14,..=,<>,<,+,/,… string“foo”,”\”q\””,…=,<>,… Basic Types Boolean Operations: e 1 andalso e 2 e 1 orelse e 2

Types in ML Every expression used in a program must be well- typed. –It is typable by the ML Type system. Declaring a type : 3 : int [1,2] : int list Usually, there is no need to declare the type in your program – ML infers it for you.

Structured Types Structured Types consist of structured values. Structured values are built up through expressions. Eg : (2+3, square 3) Structured types are denoted by type expressions. ::= | | * |  | list | …

Type of a Tuple A * B= set of ordered pairs (a,b) DataConstructor: (, )as in (a,b) Type Constructor :*as in A * B In general, (a 1,a 2,…,a n )belongs to A 1 *A 2 *…*A n. (1,2) : int * int ( , x+3,true) : real * int * bool

Type of A List [1,2,3] : int list [3.14, 2.414] : real list [1, true, 3.14] : ?? Type Constructor :list A in A-list refers to any types: (int*int) list: [ ], [(1,3)], [(3,3),(2,1)], … int list list: [ ], [[1,2]], [[1],[0,1,2],[2,3],… A list= set of all lists of A -typed values. Not well-typed!!

fac : int -> int Function Types Declaring domain & co-domain Type Constructor : -> Data Construction via : 1. Function declaration : fun f x = x + 1 ; 2. Lambda abstraction : fn x => x + 1; Value Selection via function application: f 3  4 (fn x => x + 1) 3  4 A -> B = set of all functions from A to B.

datatype Days = Mo | Tu | We | Th | Fr | Sa | Su ; Selecting a summand via pattern matching: case d ofSa => “Go to cinema” |Su => “Extra Curriculum” |_ => “Life goes on” Sum of Types Enumerated Types New Type data / data constructors

Defining an integer binary tree: datatype IntTree = Leaf int | Node of (IntTree, int, IntTree) ; fun height (Leaf x) = 0 | height (Node(t1,n,t2))= 1 + max(height(t1),height(t2)) ; Combining Sum and Product of Types: Algebraic Data Types

Some remarks A functional program consists of an expression, not a sequence of statements. Higher-order functions are first-class citizen in the language. –It can be nameless List processing is convenient and expressive In ML, every expression must be well-typed. Algebraic data types empowers the language.

Outline More about Higher-order Function Type inference and Polymorphism Evaluation Strategies Exception Handling

Function with Multiple Arguments Curried functions accept multiple arguments fun twice f x = f (f x) ; Take 2 arguments Apply 1st argument Apply 2nd argument Curried function enables partial application. let val inc2 = twice (fn x => x + x) in (inc2 1) + (inc2 2) end; val it = 12 ;

Curried vs. Uncurried Curried functions fun twice f x = f (f x) ; twice (fn x => x+x) 3  12 Uncurried functions fun twice’ (f, x) = f (f x) ; twice’ (fn x => x+x, 3)  12

Curried Functions Curried functions provide extra flexibility to the language. compose f g = fn x => f (g x)  compose f g x = f (g x)  compose f = fn g => fn x => f (g x)  compose = fn f => fn g => fn x => f (g x)

fun f(x,y) = x + y f : int*int -> int Types of Multi-Argument Funs fun g x y = x + y g : int -> int -> int (g 3) : int -> int ((g 3) 4) : int Function application is left associative; -> is right associative

Outline More about Higher-order Function Type inference and Polymorphism Evaluation Strategies Exception Handling

Type Inference ML expressions seldom need type declaration. ML cleverly infers types without much help from the user ; val it = 4 : int fun succ n = n + 1 ; val succ = fn : int -> int

Explicit types are needed when type coercion is needed. fun add(x,y : real) = x + y ; fun add(x,y) = (x:real) + y; val add = fn : real*real -> real Helping the Type Inference

Conditional expression has the same type at both branch. fun abs(x) = if x>0 then x else 0-x ; val abs = fn : int -> int Every Expression has only One Type fun f x = if x > 0 then x else [1,2,3] val f = fn : Int -> ??? This is not type-able in ML.

Example of Type Inference fun f g = g (g 1) type(g) = t = int  t2 = t2  t3 int = t2, t2 = t3 type(g) = t = int  int type(f) = t  t1 = t  t3 = (int  int)  int t  t1 t int  t2 t2  t3 t3

Three Type Inference Rules (Application rule) If f x : t, then x : t’ and f : t’ -> t for some new type t’. (Equality rule) If both the types x : t and x : t’ can be deduced for a variable x, then t = t’. (Function rule) If t  u = t’  u’, then t = t’ and u = u’.

Example of Type Inference fun f g = g (g 1) Let g : t g (g (g 1)) : t rhs So, by function declaration, we have f : t g -> t rhs By application rule, let (g 1): t (g 1) g (g 1) : t rhs  g : t (g 1) -> t rhs. By application rule, (g 1) : t (g 1)  g : int -> t (g 1). By equality rule : t (g 1) = int = t rhs. By equality rule : t g = int -> int Hence, f : (int -> int) -> int

Parametric Polymorphism fun I x = x ; val I = fn : ’a -> ’a A Polymorphic function is one whose type contains type parameters. Type parameter (I 3)(I [1,2])(I square) Interpretation of val I = fn : ’a -> ’a for all type ‘a, function I takes an input of type ‘a and returns a result of the same type ‘a. A poymorphic function can be applied to arguments of more than one type.

Polymorphic Functions A polymorphic function is one whose type contains type parameter. fun map f [] = [] | map f (x::xs) = (f x) :: (map f xs) Type of map : (’a->’b) -> [’a] -> [’b] map (fn x => x+1) [1,2,3] => [2,3,4] map (fn x => [x]) [1,2,3] => [[1],[2],[3]] map (fn x => x) [“y”,“n”] => [“y”, “n”]

Examples of Polymorphic Functions fun compose f g = (fn x => f (g x)) t1  t2  t t4  t5 t4 t5  t6 t4  t6 type(f) = t1 = t5  t6 type(g) = t2 = t4  t5 range(compose) = t = t4  t6 type(compose) = t1  t2  t = (t5  t6)  (t4  t5)  (t4  t6)

Examples of Polymorphic Functions fun compose f g = (fn x => f (g x)) Let x:t x f:t f g:t g so compose: t f -> t g ->t rhs (fn x=>f (g x)):t rhs => t rhs = t x ->t (f(gx)) (g x):t (gx) ==> g: t x ->t (gx) and t g = t x ->t (g x) (f (g x)):t (f(gx)) ==> f:t (gx) ->t (f(gx)) and t f = t (gx) ->t (f(gx)) compose: (t (gx) ->t (f(gx)) )->(t x ->t (gx) )->(t x ->t (f(gx)) ) Rename the variables: compose: (’a->’b)->(’c->’a)->(’c->’b)

Outline More about Higher-order Function Type inference and Polymorphism Evaluation Strategies Exception Handling

Approaches to Expression Evaluation Different approaches to evaluating an expression may change the expressiveness of a programming language. Two basic approaches: –Innermost (Strict) Evaluation Strategy SML, Scheme –Outermost (Lazy) Evaluation Strategy Haskell, Miranda, Lazy ML

Innermost Evaluation Strategy To Evaluate the call : –(1) Evaluate ; –(2) Substitute the result of (1) for the formals in the body ; –(3) Evaluate the body of ; –(4) Return the result of (3) as the answer. let fun f x = x x in f (2 + 3) end ; body formals actuals

fun f x = x x ; f (2+3) ==> f (5) ==> ==> 12 fun g x y = if (x < 3) then y else x; g 3 (4/0) ==> g 3  ==>  Also referred to as call-by-value evaluation. Occasionally, arguments are evaluated unnecessarily.

Outermost Evaluation Strategy To Evaluate : (1) Substitute actuals for the formals in the body ; (2) Evaluate the body ; (3) Return the result of (2) as the answer. fun f x = x x ; f (2+3) ==> (2+3) (2+3) ==> 12 fun g x y = if x < 3 then y else x ; g 3 (4/0) ==> if 3 < 3 then (4/0) else 3 ==> 3

It is possible to eliminate redundant computation in outermost evaluation strategy. fun f x = x x ; f (2+3) ==> x x ==> x ==> 7 + x ==> ==> 12 5 x=(2+3) Note: Arguments are evaluated only when they are needed.

Why Use Outermost Strategy? Closer to the meaning of mathematical functions fun k x y = x ; val const1 = k 1 ; val const2 = k 2 ; Better modeling of real mathematical objects val naturalNos = let fun inf n = n :: inf (n+1) in inf 1 end ;

Hamming Number List, in ascending order with no repetition, all positive integers with no prime factors other than 2, 3, or 5. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,...

n as a prime factor fun scale n [] = [] | scale n (x::xs) = (n*x) :: (scale n xs) scale 2 [1,2,3,4,5] = [2,4,6,8,10] scale 3 [1,2,3,4,5] = [3,6,9,12,15] scale 3 (scale 2 [1,2,3,4,5]) = [6,12,18,24,30]

Merging two Streams fun merge [] [] = [] | merge (x::xs) (y::ys) = if x < y then x :: merge xs (y::ys) else if x > y then y :: merge (x::xs) ys else x :: merge xs ys merge [2,4,6] [3,6,9] = [2,3,4,6,9]

Hamming numbers val hamming = 1 :: merge (scale 2 hamming) (merge (scale 3 hamming) (scale 5 hamming)) :: 1 merge scale 3 scale 5 scale 2

Outline More about Higher-order Function Type inference and Polymorphism Evaluation Strategies Exception Handling

Handle special cases or failure (the exceptions) occurred during program execution. hd []; uncaught exception hd Exception can be raised and handled in the program. exception Nomatch; exception Nomatch : exn fun member(a,x) = if null(x) then raise Nomatch else if a = hd(x) then x else member(a,tl(x))

fun member(a,x) = if null(x) then raise Nomatch else if a = hd(x) then x else member(a,tl(x)) member(3,[1,2,3,1,2,3]) ; val it = [3,1,2,3] : int list member(4,[]) ; uncaught exception Nomatch member(5,[1,2,3]) handle Nomatch=>[]; val it = [] : int list

Conclusion More about Higher-order Function –Curried vs Uncurried functions –Full vs Partial Application Type inference and Polymorphism –Basic Type inference rules –Polymorphic functions Evaluation Strategies –Innermost –Outermost Exception Handling is available in ML