Patterns The Essence of Functional Programming

Similar documents
A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Lecture 6: Sequential Sorting

Shell CSCE 314 TAMU. Functions continued

ML Built-in Functions

Mini-ML. CS 502 Lecture 2 8/28/08

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Programming in Haskell Aug-Nov 2015

Begin at the beginning

CS 320: Concepts of Programming Languages

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

CSE341 Spring 2017, Midterm Examination April 28, 2017

An introduction introduction to functional functional programming programming using usin Haskell

CSE 341 : Programming Languages Midterm, Spring 2015

CSc 372 Comparative Programming Languages

More fun with recursion

CS 321 Programming Languages

Datatype declarations

Exercises on ML. Programming Languages. Chanseok Oh

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CSc 372. Comparative Programming Languages. 15 : Haskell List Comprehension. Department of Computer Science University of Arizona

Assignment 0. Computer Science 52. Due Friday, September 7, 2018, at 5:00 pm

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

CS558 Programming Languages

CSE341 Autumn 2017, Midterm Examination October 30, 2017

CSE341 Spring 2016, Midterm Examination April 29, 2016

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

Programming Languages ML Programming Project Due 9/28/2001, 5:00 p.m.

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

Introduction to Programming: Lecture 6

Lab 9: More Sorting Algorithms 12:00 PM, Mar 21, 2018

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Chapter 3 Linear Structures: Lists

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

CSE341, Fall 2011, Midterm Examination October 31, 2011

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

Announcements. Scope, Function Calls and Storage Management. Block Structured Languages. Topics. Examples. Simplified Machine Model.

About this exam review

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages

A general introduction to Functional Programming using Haskell

Functional Programming

All the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)

Lists. Michael P. Fourman. February 2, 2010

Scope, Functions, and Storage Management

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.

Functional Programming. Pure Functional Programming

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

CSE341, Fall 2011, Midterm Examination October 31, 2011

Chapter 3 Linear Structures: Lists

UNIVERSITETET I OSLO

15 150: Principles of Functional Programming Sorting Integer Lists

Shell CSCE 314 TAMU. Haskell Functions

Functional Programming. Pure Functional Programming

Handout 2 August 25, 2008

Functors signature Order = sig functor name type elem (structname:signature) = structure definition; val le : elem*elem -> bool end; elem

Informatics 1 Functional Programming Lecture 12. Data Abstraction. Don Sannella University of Edinburgh

The Worker/Wrapper Transformation

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

Fall 2018 Lecture N

Module 08: Searching and Sorting Algorithms

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Searching in General

CS 340 Spring 2019 Midterm Exam

Programming Languages and Techniques (CIS120)

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

An introduction to functional programming. July 23, 2010

Recap: Functions as first-class values

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CSc 372, Spring 1996 Mid-term Examination Solution Key

Programming Languages

Thinking Induc,vely. COS 326 David Walker Princeton University

5. Selection: If and Switch Controls

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011

CSE 130 [Winter 2014] Programming Languages

Programming Languages

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

CIS 120 Midterm I February 16, 2015 SOLUTIONS

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

02157 Functional Programming. Michael R. Ha. Lecture 2: Functions, Types and Lists. Michael R. Hansen

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

CS 320 Homework One Due 2/5 11:59pm

Imperative Paradigm. Syntax. Role of Programming Languages. Expressions. Expressions. Role of Programming Languages. Symbols.

Programovací jazyky F# a OCaml. Chapter 5. Hiding recursion using function-as-values

Online Resource. Online introductory book on programming in SML (Standard ML): online.pdf

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

CS 11 Ocaml track: lecture 2

Section 7.3 Divide-and-Conquer Algorithms and Recurrence Relations. 0,a m. - Division into thirds gives m = 3

CSc 372, Fall 2006; Quiz 1 Time: 3:00; Value: 2 points. 1. What is a fundamental difference between the if-then-else constructs in Java (or C) and ML?

Questions & Answers 28 Sept.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Transcription:

Patterns The Essence of Functional Programming Up to now we have defined functions in a very traditional way: function name + variable name parameters Read Chap 7 In functional programming we can exploit the structure of objects during a function definition by using patterns and pattern matching. Example: no pattern matching, factorial - fun fact(x) = if x = 0 then 1 else x*fact(x-1); Example: with pattern matching, factorial - fun fact 0 = 1 fact n = n * fact(n-1); x! 1 if x = 0 x*(x-1)! otherwise Very simple pattern: either it is 0 or not.

Patterns In order to use patterns we need to extend our ML syntax for function definitions: <fun-def> ::= fun <fun-bodies> <fun-bodies> ::= <fun-body> <fun-body> <fun-bodies> <fun-body> ::= <fun-name> <pattern> = <expression> <pattern> ::= any function and operator free expression (constructors are allowed). Valid Patterns: 1 (a,b) [2,3] q::rest Invalid Patterns: 1+a f(q)

Patterns Example: Pattern matching on lists. Write a function sumlist that accepts a list of integer values and returns the sum of the integers on the list. - fun sumlist ([ ]) = 0 sumlist(x :: xs) = x + sumlist(xs);

Patterns Example: write a function that reverses a given list. - fun reverse ([ ]) = [ ] reverse (x :: xs) = reverse(xs) @ [x];

Patterns Example: match on nested structures. Assume we have a list of persons [(32,185, married, pilot ),(28,160, not-married, cook ),...] we want to write a function that returns the age of the first person on the list. - fun get1stage ((age,weight,mstat,profession)::otherpersons) = age; here we pattern match on the list as well as on the tuples that make up the list - fun get1stage (L) = #1 hd(l); same function no pattern matching Note: here we assume that the list of persons is never empty!

Anonymous Variables Consider the following program: - fun f (0) = zero f (x) = non-zero ; The variable x is never used on the right side of the equation; bad programming practice. We can rewrite this program using an anonymous variable: - fun f (0) = zero f ( _ ) = non-zero ; Here we pattern match on the structure but we don t exactly care what the precise values are.

Patterns Pattern matches can also occur in other places in functional programs. Consider, - val (age,weight,mstat,profession) = (38,185, married, pilot ); pattern! val age = 38 : int val weight = 185 : int val mstat = "married" : string val profession = "pilot" : string This is different from - val joe = (38,185, married, pilot ); val joe = (38,185, married, pilot ) : int * int * string * string

Local Definitions: Let Stmt The aim is to limit the scope of a definition. Syntax: <let-expr> ::= let <definitions> in <expr> <definitions> ::= any valid variable or function definition <expr> ::= any valid expression Note: the value of <expr> is the return value of <let-expr>.

Pattern Matching with Let Stmt Example: Given a list of elements, write a function that returns two lists,, each with half the elements of the original list. - fun halve ([ ]) = ([ ], [ ]) halve ([a]) = ([a], []) halve (a::b::rest) = let val (x,y) = halve(rest) in (a::x,b::y) end; x and y are local variables.

Merge Sort! The halve function divides a list into two nearly-equal parts! This is the first step in a merge sort! For practice, we will look at the rest

Example: Merge fun merge ([], ys) = ys merge (xs, []) = xs merge (x::xs, y::ys) = if (x < y) then x :: merge(xs, y::ys) else y :: merge(x::xs, ys);! Merges two sorted lists! Note: default type for < is int

Example: Merge Sort fun mergesort [] = [] mergesort [a] = [a] mergesort thelist = let val (x,y) = halve thelist in merge(mergesort x, mergesort y) end;! Merge sort of a list! Type is int list -> int list, because of type already found for merge

Merge Sort At Work - fun mergesort [] = [] = mergesort [a] = [a] = mergesort thelist = = let = val (x, y) = halve thelist = in = merge(mergesort x, mergesort y) = end; val mergesort = fn : int list -> int list - mergesort [4,3,2,1]; val it = [1,2,3,4] : int list - mergesort [4,2,3,1,5,3,6]; val it = [1,2,3,3,4,5,6] : int list

Nested Function Definitions! You can define local functions, just like local variables, using a let! You should do it for helper functions that you don't think will be useful by themselves! We can hide halve and merge from the rest of the program this way! Another potential advantage: inner function can refer to variables from outer one (as we will see in Chapter 12)

Merge Sort fun mergesort [] = [] mergesort [e] = [e] mergesort thelist = let fun halve [] = ([], []) halve [a] = ([a], []) halve (a::b::cs) = let val (x, y) = halve cs in (a::x, b::y) end; fun merge ([], ys) = ys merge (xs, []) = xs merge (x::xs, y::ys) = if (x < y) then x :: merge(xs, y::ys) else y :: merge(x::xs, ys); val (x, y) = halve thelist in merge(mergesort x, mergesort y) end;

Exercise Write the function less(e,l) that returns a list of integers from the list L each of which is less than the value e.

Homework Assignment #6 see website use pattern matching! Midterm coming up end of October