Chapter 9: Functional Programming in a Typed Language.

Slides:



Advertisements
Similar presentations
Modern Programming Languages, 2nd ed.
Advertisements

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 [3,4]
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.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
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.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
String is a synonym for the type [Char].
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
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 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
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.
5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
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.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
FUNCTIONAL PROGRAMMING IN ERLANG ID1218 Lecture Christian Schulte Software and Computer Systems School of Information and.
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Functional Programming Element of Functional Programming.
Chapter 15: Functional Programming Languages
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
ISBN Chapter 15 Functional Programming Languages.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Chapter Fifteen: Functional Programming Languages Lesson 12.
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.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
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.
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
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,
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Functional Programming
String is a synonym for the type [Char].
Conditional Expressions
Functional Programming
Principles of programming languages 12: Functional programming
ML: a quasi-functional language with strong typing
A lightening tour in 45 minutes
ML Programming Language Design and Implementation (4th Edition)
PROGRAMMING IN HASKELL
Mini Language Interpreter Programming Languages (CS 550)
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.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Types and Classes in Haskell
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Constructors Construct a value of a given type.
CSE 3302 Programming Languages
Announcements Quiz 5 HW6 due October 23
List and list operations (continue).
Presentation transcript:

Chapter 9: Functional Programming in a Typed Language

Essence What is the function that must be applied to the initial machine state by accessing the initial set of variables and combining them in a specific ways in order to get an answer? Languages that emphasize this view are called functional languages

Essence Program development proceeds by developing functions from previously developed function in order to build more complex functions that manipulate the initial set of data until the final function can be used to compute and answer for the initial data

Standard ML ML is the working language of this chapter because it best describes the topic of functional programming. The name of ML is an acronym for Meta Language. ML was initially designed for computer- assisted reasoning.

Functional Programming Precise definition is up to debate “pure functional programming” - do not allow side effects Scheme (Lisp), ML are all impure, do allow side effects There are some “pure”, Haskell, Miranda However when we compare programs written in the pure and programs written in the pure part of Scheme, Lisp and ML there is little difference

9.1 Exploring a List Lists are considered to be the original data structure of functional programming. Most of the functions explore the structure of the list. –Examples of these functions include: APPEND FUNCTION REVERSE FUNCTION

Operations on Lists ML lists are written in between brackets and separated by commas. –Example: [11, 23, 34], [ ] A list has the form of a::y. Where a is the head of the list and y represents the tail of the list. –Example: [7] => 7::[ ] –Example: [11,23,34] => 11::34

Functions for Lists NULL (null) HEAD (hd) TAIL (tl) CONS (::) Test for emptiness. Return the first element. Return all except the first element. Infix list constructor

Linear Functions on Lists Most functions consider the elements of a list one by one. In other words, they behave as follows: –fun length(x) = if null (x) then 0 else 1 + length(tl(x)) (Recursive) An empty list has a length of 0. Length of a nonempty list x is 1 greater than the length of the tail of x.

Definition of Append & Reverse APPEND: fun append(x, z) = if null(x) then z else hd (x) :: append(tl(x), z) REVERSE: fun reverse(x, z) = if null(x) then z else reverse(tl(x), hd(x) :: z)

Append Function The append function uses symbol which combines two lists. For example: –append ([1,2], [3, 4, 5]) => [1, [3, 4, 5] => [1, 2, 3, 4, 5] Other examples: –append ([ ], z) => z –append (a::y, z) => a :: append (y, z)

Reverse Function The function reverse can be used to reverse a list. Following examples: –reverse([ ], z) => z –reverse(a::y) => reverse(y, a :: y) The reverse function is related to the ML function rev, which basically implements in the same way. For example: –rev(x) => reverse(x, [ ])

Reverse/Append Phases Linear functions like reverse and append contain two different phases: –1. A winding in which the function examines the tail of the list, and –2. an unwinding phase in which control unwinds back to the beginning of the list.

Reverse/Append Phases Example of the reverse winding phase: –reverse([2, 3, 4], [1]) => reverse([3, 4], [2, 1]) => reverse([4], [3, 2, 1]) => reverse([ ], [4, 3, 2, 1]) => [4, 3, 2, 1] Example of the append winding phase: –append([2, 3, 4], [1]) calls append([3, 4], [1]) append([3, 4], [1]) calls append([4], [1]) append([4], [1]) calls append([ ], [1])

Reverse/Append Functions Here is the unwinding of the previous function. –append([ ], [1]) => [1] append([4], [1]) => [4, 1] append([3, 4], [1]) => [3, 4, 1] append([2, 3, 4], [1]) => [2, 3, 4, 1]

9.2 Function Declaration by Cases The format of function declarations is: fun = An example of this format is the successor function: fun succ n = n + 1 The application of a function f to an argument x can be written either with parentheses f(x), or without f x.

Function Applications Function application has higher precedence than the following operators:, >=, > +, -, ^ *, /, div, mod Examples: 3 * succ 4; => 3 * 5 => 15 3 * succ 4 :: [ ]; => 3 * list [5] => list [15]

Patterns Functions with more than one argument can be declared using the following syntax: fun = A has the form of an expression made up of variables, constants, pairs of tuples, and list constructors. Examples: (x,y), (a :: y), (x, _)

Patterns and Case Analysis Patterns and case analysis give ML a readable notation. Cases are separated by a vertical bar. fun length([ ]) = 0 | length(a :: y) = 1 + length(y) The declaration of a function in ML can have the following form. fun f = | f = …

Patterns and Case Analysis The ML interpreter complains if the cases in a function declaration are not complete, or in other words taking each case into consideration. Example: fun head (a :: y) = a; [WARNING] (Not a case for empty lists!!) Other warnings come from misspellings or repeated formals in patterns such as: fun f(nul) = 0 …null misspelled strip(1, [1, 1, 2]) = … 1 is repeated in formal

9.3 Functions as First-Class Values This section includes a small library with useful functions such as map, remove_if, and reduce. The tools may use functions as arguments. A function is called “higher order” if either its arguments or its results are themselves functions.

Mapping Functions A “filter” is a function that copies a list, and makes useful changes to the elements as they are copied. The idea behind the function map is for each element a of a list, do something with a and return a list of the results. For example: map square [1, 2, 3, 4] => [1, 4, 9, 16]

The Utility of Map The beauty of functional programming lies in the ability to combine functions in interesting ways. Examples use the following functions: –Square Multiply an integer argument by itself –First Return the first element of a pair –Second Return the second element of a pair. Before defining new functions, we will consider a short example involving the map.

The Utility of Map Example: hd [ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34] ]; => [11, 12, 13, 14] map hd [ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34] ]; => [11, 21, 31]

Anonymous Functions In ML, an anonymous function, a function without a name, has the form fn => Example: fn x => x * 2 These functions are helpful for adapting existing functions so they can be used together with tools like map. map (fn x => x*2) [1,2,3,4,5]; –[2,4,6,8,10]

Selective Copying The “remove_if” function is another higher order function that removes elements from lists if some condition holds. It is used in the same fashion as map. Example: fun odd = (x mod 2) = 1 remove_if odd [0, 1, 2, 3, 4, 5]; => [0, 2, 4]

Accumulate a Result The “reduce” function accumulates a result from a list. Most of the time this function is used with a few simple functions such as sum_all, add, multiply, etc. For example: reduce add [1, 2, 3, 4, 5] 0; => 15

9.4 ML: Implicit Types Even when ML checks its types at compile time, ML expressions are surprising free of type declarations. This section will consider two aspects of types in ML. –Inference –Polymorphism

Type Inference ML refers types when the user has not specified the type. For example: 3 * 4; => val it = 12 : int (Since the 3 and 4 are integers the product yields an integer) The type of an expression can be specified by writing : Overloading yields an error. For example: fun add (x, y) = x + y; => Error

Parametric Polymorphism A polymorphic function can be applied to arguments of more than one type. We concentrate on parametric polymorphism, a special kind of polymorphism, in which type expressions are parameterized. –Example: alpha -> alpha (with parameter alpha)

Parametric Polymorphism Example: fun length (nil) = 0 | length (a :: y) = 1 + length (y); => fn : (alpha-> int) Example: length ([“hello”, “world”]); => 2 : int (remember the # in the list) (Holds the strings as ints.)

9.5 Data Types Datatype declarations in ML are useful for defining types that correspond to data structures. Examples of data structures include binary trees, arithmetic expressions, etc.

Value Constructors A datatype in ML introduces a basic type as a set of values. Here is an example of a datatype direction. datatype direction = north| south| east| west =>{ north, south, east, west } These values become atomic; they are constants with no components.

Value Constructors with Parameters A datatype declaration involves two parts. 1.A type name. 2.A set of value constructors for creating values of that type. Value Constructors can have parameters, as in the following declaration of datatype bitree. datatype bitree = leaf| nonleaf of bitree*bitree In words, a value of type bitree is either the constant leaf or it is constructed by applying nonleaf to a pair of values of type bitree.

Binary Trees Leaf Nonleaf (leaf, leaf) Nonleaf (nonleaf (leaf, leaf), leaf) Nonleaf (leaf, nonleaf (leaf, leaf)) …

Operations on Constructed Values Patterns can be used to examine the structure of a constructed value. Example: nonleaf ( leaf, nonleaf (leaf, leaf)) fun leafcount (leaf) = 1 | leafcount (nonleaf (s,t)) = leafcount (s) + leafcount (t); => 3 leaves

Differentiation: A Traditional Example Symbolic differentiation of expressions like x*(x+y) is a standard example. An expression is either a constant, variable, sum, or a product. For example: datatype expr = constant of int | variable of string | sum of expr *expr | product of expr * expr; val zero constant (0); (Declaration) => val zero = constant 0 : expr

Differentiation: A Traditional Example Example where d => derivative: fun d x (constant_) = zero (This statement reads the derivative of any constant is zero.)

Polymorphic Datatypes Lists are polymorphic. In other words, there can be lists of integers, lists of strings, lists of type alpha, for any type alpha. Example of a datatype declaration would be: datatype alpha List = Nil | Cons of alpha * (alpha List) Example: Nil : alpha List (This statement reads that the value of Nil must denote an empty list, where List is of alpha datatype.)

Functional Programming Exception handling will be in a separate lecture look at how little quilt is implemented in ML starting in section 9.7 Do exercise 9.1 page 380. Remember use existing ML functions to create these