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.

Slides:



Advertisements
Similar presentations
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Advertisements

Modern Programming Languages, 2nd ed.
Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Higher-order functions in OCaml. Higher-order functions A first-order function is one whose parameters and result are all "data" A second-order function.
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.
Writing functions in OCaml. Defining a simple function # let add (x, y) = x + y;; val add : int * int -> int = Notice what this says: –add is a value.
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.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
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 =
Chapter ElevenModern Programming Languages1 A Fourth Look At ML.
A Fourth Look At ML Chapter ElevenModern Programming Languages, 2nd ed.1.
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.
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.
Map and Fold Building Powerful Abstractions. Hello. I’m Zach, one of Sorin’s students.
CSE341: Programming Languages Lecture 6 Tail Recursion, Accumulators, Exceptions Dan Grossman Fall 2011.
CSE341: Programming Languages Lecture 5 Pattern-Matching Dan Grossman Fall 2011.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
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.
1 Functional languages (e.g. Scheme, ML) Scheme is a functional language. Scheme is based on lambda calculus. lambda abstraction = function definition.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
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,
CSE 341 : Programming Languages Lecture 6 Fancy Patterns, Exceptions, Tail Recursion Zach Tatlock Spring 2014.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
The Evolution of Programming Languages Day 2 Lecturer: Xiao Jia The Evolution of PLs1.
Patterns in OCaml 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.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
1 Functional Programming Lecture 6 - Algebraic Data Types.
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.
CSE 341 : Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Spring 2014.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
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:
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Cs776(Prasad)L6sml971 SML-97 Specifics SML/NJ 110.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
ML: a quasi-functional language with strong typing
ML Again ( Chapter 7) Patterns Local variable definitions
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE 341 Lecture 3 let expressions; pattern matching Ullman
FP Foundations, Scheme In Text: Chapter 14.
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE 341 Section 5 Winter 2018.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2018.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE 341 Section 2 Nick Mooney Spring 2017
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
Lisp.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2019.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2017.
Presentation transcript:

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 formal parameters –Formal parameters must be variables (in C) Here's a function call: –total = add (total, 5); –total and 5 are the actual parameters –Actual parameters typically can be expressions

Parameters are patterns In most conventional languages, formal parameters must be variables –Example: x and y in f(x, y) are both variables In ML, all functions take a single parameter For example, in fun add (x, y) = x + y; we say that (x, y) is one parameter, a tuple But (x, y) is not a variable......it is a pattern

The unit as parameter Consider: fun five ( ) = 5; The single parameter is the unit, ( ) But the unit is a value, that is, a constant In ML, a formal parameter (not just an actual parameter) may be a constant Parameter transmission uses pattern matching

Patterns separate cases in Prolog Prolog passes parameters by unification Unification is a very general and powerful kind of pattern matching Parameters are used to separate a task into cases, for example, –member(X, [X | _]). member(X, [_ | Y]) :- member(X, Y).

Patterns separate cases in Java Java doesn't do pattern matching on parameters, but... Java does allow methods to be overloaded Overloaded methods have different signatures –The signature describes the number and type of parameters This is a primitive kind of pattern matching In a sense, it separates method calls into cases

ML allows multiple patterns Pattern matching is not guaranteed to succeed It's OK if a Prolog predicate fails, but......an ML function must return a value Therefore, ML must support multiple patterns in a function definition Also, ML must ensure that the patterns are exhaustive, i.e. some pattern must match

Factorial fun factorial 0 = 1 | factorial n = n * factorial (n - 1); The vertical bar separates cases The function name is repeated There's only one semicolon, at the end Patterns are tried in order, therefore......specific cases must precede general cases

Lists as patterns Use the cons operator :: to form patterns The pattern (x :: xs) matches a nonempty list fun listSize [ ] = 0 | listSize (x::xs) = 1 + listSize xs; –val listSize : 'a list -> int = fn listSize ["a", "b", "c"]; –val it : int = 3

Exhaustive patterns fun car (x::xs) = x; –warning: Match not exhaustive missing constructors of type 'a list : nil val car : 'a list -> 'a = fn car ["a", "b", "c"]; –val it : string = "a" ML warns you but lets you continue

Last element of a list fun last [x] = x | last (x::xs) = last xs; –warning: Match not exhaustive missing constructors of type 'a list : nil val last : 'a list -> 'a = fn last ["a", "b", "c"]; –val it : string = "c" Notice the use of [x] and (x::xs) as patterns [x] and (x::nil) are really the same thing

Doubling each element of a list fun doubleAll [ ] = [ ] | doubleAll (h::t) = 2 * h :: (doubleAll t); –val doubleAll : int list -> int list = fn doubleAll [1,2,3,4,5]; –val it : int list = [2, 4, 6, 8, 10]

as patterns as parameters A pattern as a formal parameter breaks apart the components of the actual parameter Using (x, y) gives us names for the two parts (x :: xs) gives us names for the head and tail We may also want a name for the whole thing identifier as pattern lets us do both Example: theList as (head :: tail)

Example: merge fun merge(nil, M) = M | merge(L, nil) = L | merge(L as x::xs, M as y::ys) = if x < y then x::merge(xs, M) else y::merge(L, ys); –val merge : (int list * int list) -> int list = fn Source: Elements of ML Programming, J. Ullman

Match expressions A match consists of rules separated by | A rule has the form pattern => result –pattern1 => result1 | pattern2 => result2 |... patternN => resultN The results must all be of the same type The patterns should be exhaustive

case expressions A match all by itself isn't a complete expression A case expression has the form: case expression of match Patterns are tried in the order they are given When a match is found, the corresponding result is evaluated and returned as the result If nothing matches, a Match exception is raised We haven't covered exceptions yet

if...then...else... expressions if expr1 then expr2 else expr3 is actually syntactic sugar for case expr1 of true => expr2 | false => expr3 If you make an error in an if expression, the compiler reports it as an error in a case expression

Functions using fn fun f(pattern1) = expr1 | f(pattern2) = expr2; is actually syntactic sugar for val rec f = fn pattern1 => expr1 | pattern2 => exprn2; Note the use of val, fn, and rec rec is only required for recursive functions

ML is purely functional The if and case expressions are special cases of a match; so is fun Arithmetic operators such as + are syntactic sugar for functions –Operators can be used as functions: op + (a, b) In ML, "expressions" are really functions, and basically everything is a function

The End