1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 21: Functional Programming in Python COMP 144 Programming Language Concepts Spring.

Slides:



Advertisements
Similar presentations
Haskell Lets review some of the Haskell concepts you have been learning on your own. The answers are included, but try it yourself first.
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.
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
Exercises – don’t use built in functions for these as we want the practice Write a recursive function to add up all the numbers in a list "flatten" a list.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 20: Lists and Higher-Order Functions in Haskell COMP 144 Programming Language Concepts.
CSE 341 Lecture 6 exceptions; higher order functions; map, filter, reduce Ullman 5.2, 5.4 slides created by Marty Stepp
Advanced Programming Andrew Black and Tim Sheard Lecture 4 Intro to Haskell.
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 19: Functions, Types and Data Structures in Haskell COMP 144 Programming Language.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
List Comprehensions. Python’s higher-order functions  Python supports higher-order functions that operate on lists similar to Scheme’s >>> def square(x):
Data Structures Akshay Singh.  Lists in python can contain any data type  Declaring a list:  a = [‘random’,’variable’, 1, 2]
CS 2104 : Prog. Lang. Concepts. Functional Programming I Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
Com Functional Programming Higher Order Functions and Computation Patterns (I) Marian Gheorghe Lecture 10 Module homepage Mole &
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Scheme & Functional Programming. ( ) >> 64 ( ) >> 666 (* ) >> 1200 (+ (* 3 5) (- 10 6)) >> 19.
Python functional programming. Functions are first-class objects Functions can be used as any other datatype, eg: Arguments to function Return values.
Sound Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen Chalmers University of Technology.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
Modeling with Haskell Scientific Seminar 03/04 Gerhard Navratil.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
CS 603: Programming Language Organization Lecture 10 Spring 2004 Department of Computer Science University of Alabama Joel Jones.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
CS 2104 – Prog. Lang. Concepts Functional Programming II Lecturer : Dr. Abhik Roychoudhury School of Computing From Dr. Khoo Siau Cheng’s lecture notes.
CS 603: Programming Language Organization Lecture 9 Spring 2003 Department of Computer Science University of Alabama Joel Jones.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
1 Static Contract Checking for Haskell Dana N. Xu University of Cambridge Joint work with Simon Peyton Jones Microsoft Research Cambridge Koen Claessen.
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.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
List Operations CSCE 314 Spring CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
CSE 3302 Programming Languages Chengkai Li Spring 2008 Functional Programming Language: Haskell (cont’d) Lecture 20 – Functional Programming, Spring 2008.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Functional Programming in Python Abhishek Dasgupta Indian Institute of Science Education and Research, Kolkata.
Lecture 14: Advanced Topic: Functional Programming
Higher Order Functions
Recursion.
Introduction to Higher Order (Functional Programming) (Python) part 2
dr Robert Kowalczyk WMiI UŁ
Functional Programming Lecture 12 - more higher order functions
Haskell Chapter 4.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
COP4020 Programming Languages
CHAPTER FOUR Functions.
Important Concepts from Clojure
Important Concepts from Clojure
PROGRAMMING IN HASKELL
Higher Order Functions
PROGRAMMING IN HASKELL
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CSCE 314: Programming Languages Dr. Dylan Shell
Higher Order Functions
CS 457/557: Functional Languages Folds
HIGHER ORDER FUNCTIONS
CSE 3302 Programming Languages
Lambda Functions, MapReduce and List Comprehensions
PROGRAMMING IN HASKELL
Lecture 7: Python’s Built-in Types and Basic Statements
Higher-Order Functions in Haskell
functions are also data! other functions as input!
Presentation transcript:

1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 21: Functional Programming in Python COMP 144 Programming Language Concepts Spring 2002 Felix Hernandez-Campos March 1 The University of North Carolina at Chapel Hill

2 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Haskell Lists can be defined by enumeration using list comprehensionsLists can be defined by enumeration using list comprehensions –Syntax: [ f x | x <- xs ] [ (x,y) | x <- xs, y <- ys ]Generator

3 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Python >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit']

4 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Python >>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18] >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x >> [3*x for x in vec if x < 2][]

5 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Python >>> [{x: x**2} for x in vec] [{2: 4}, {4: 16}, {6: 36}] >>> [[x,x**2] for x in vec] [[2, 4], [4, 16], [6, 36]] >>> [x, x**2 for x in vec] # error - parens required for tuples File " ", line 1, in ? [x, x**2 for x in vec] ^ SyntaxError: invalid syntax

6 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Python >>> [(x, x**2) for x in vec] [(2, 4), (4, 16), (6, 36)] >>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] >>> [x*y for x in vec1 for y in vec2] [8, 6, -18, 16, 12, -36, 24, 18, -54] >>> [x+y for x in vec1 for y in vec2] [6, 5, -7, 8, 7, -5, 10, 9, -3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8, 12, -54]

7 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehension Python Quicksort exampleQuicksort example quicksort [] = [] quicksort (x:xs) = quicksort [y | y <- xs, y<x ] ++ [x] ++ quicksort [y | y =x]

8 COMP 144 Programming Language Concepts Felix Hernandez-Campos List Comprehensions Python def quicksort(list): if (len(list) == 0): if (len(list) == 0): return [] return [] else: else: pivot = list[0] pivot = list[0] l = [] l = [] l = l + quicksort([x for x in list[1:] if x < pivot]) l = l + quicksort([x for x in list[1:] if x < pivot]) l.append(pivot) l.append(pivot) l = l + quicksort([x for x in list[1:] if x >= pivot]) l = l + quicksort([x for x in list[1:] if x >= pivot]) return l return l

9 COMP 144 Programming Language Concepts Felix Hernandez-Campos Higher-Order Functions Higher-order functions are functions that take other functions as argumentsHigher-order functions are functions that take other functions as arguments They can be use to implement algorithmic skeletonsThey can be use to implement algorithmic skeletons –Generic algorithmic techniques Three predefined higher-order functions are specially useful for working with listThree predefined higher-order functions are specially useful for working with list –map –fold –filter

10 COMP 144 Programming Language Concepts Felix Hernandez-Campos Map Haskell Applies a function to all the elements of a listApplies a function to all the elements of a list map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x : xs) = f x : map f xs –Examples map square [9, 3] [81, 9] map square [9, 3]  [81, 9] map (<3) [1, 5] [True, False] map (<3) [1, 5]  [True, False]

11 COMP 144 Programming Language Concepts Felix Hernandez-Campos Map Python "map(function, sequence)" calls function(item) for each of the sequence's items and returns a list of the return values."map(function, sequence)" calls function(item) for each of the sequence's items and returns a list of the return values. For example, to compute some cubes:For example, to compute some cubes: >>> def cube(x): return x*x*x... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

12 COMP 144 Programming Language Concepts Felix Hernandez-Campos Map Python More than one sequence may be passedMore than one sequence may be passed the function must then have as many arguments as there are sequencesthe function must then have as many arguments as there are sequences It is called with the corresponding item from each sequence (or None if some sequence is shorter than another). If None is passed for the function, a function returning its argument(s) is substituted.It is called with the corresponding item from each sequence (or None if some sequence is shorter than another). If None is passed for the function, a function returning its argument(s) is substituted.

13 COMP 144 Programming Language Concepts Felix Hernandez-Campos Map Python Combining these two special cases, we see that "map(None, list1, list2)" is a convenient way of turning a pair of lists into a list of pairs.Combining these two special cases, we see that "map(None, list1, list2)" is a convenient way of turning a pair of lists into a list of pairs. For exampleFor example >>> seq = range(8) >>> def square(x): return x*x... >>> map(None, seq, map(square, seq)) [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]

14 COMP 144 Programming Language Concepts Felix Hernandez-Campos Zip Zip combines two lists into a list of pairsZip combines two lists into a list of pairs zip :: [a] -> [b] -> [(a,b)] zip [] ys = [] zip (x:xs) [] = [] zip (x:xs) (y:ys) = (x,y):zip(xs,ys)

15 COMP 144 Programming Language Concepts Felix Hernandez-Campos Filter Haskell Extracts the elements of a list that satisfy a boolean functionExtracts the elements of a list that satisfy a boolean function filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x : xs) = if p x then x : filter p xs else filter p xs –Example filter (>3) [1, 5, -5, 10, -10] [5, 10] filter (>3) [1, 5, -5, 10, -10]  [5, 10]

16 COMP 144 Programming Language Concepts Felix Hernandez-Campos Filter Python filter(function, sequence)" returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true.filter(function, sequence)" returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true. For example, to compute some primes:For example, to compute some primes: >>> def f(x): return x % 2 != 0 and x % 3 != 0... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]

17 COMP 144 Programming Language Concepts Felix Hernandez-Campos Fold Takes in a function and folds it in between the elements of a listTakes in a function and folds it in between the elements of a list Two flavors:Two flavors: –Right-wise fold: [x 1, x 2, x 3 ] x 1  (x 2  (x 3  e)) –Right-wise fold: [x 1, x 2, x 3 ]  x 1  (x 2  (x 3  e)) Fold Operator Base Element foldr :: (a -> b -> b) -> b -> [a] -> [a] foldr f e [] = [] foldr f e (x:xs) = f x (foldr f e xs)

18 COMP 144 Programming Language Concepts Felix Hernandez-Campos Foldl Left-wise fold: [x 1, x 2, x 3 ] ((e  x 1 )  x 2 )  x 3Left-wise fold: [x 1, x 2, x 3 ]  ((e  x 1 )  x 2 )  x 3 foldl :: (a -> b -> b) -> b -> [a] -> [a] foldl f e [] = [] foldl f e (x:xs) = foldl f (f e x) xs ExampleExample max a b = if a > b then a else b foldl max 0 [1,2,3] 3 foldl max 0 [1,2,3]  3

19 COMP 144 Programming Language Concepts Felix Hernandez-Campos Folding in Python: Reduce "reduce(func, sequence)" returns a single value constructed by calling the binary function func on the first two items of the sequence, then on the result and the next item, and so on."reduce(func, sequence)" returns a single value constructed by calling the binary function func on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:For example, to compute the sum of the numbers 1 through 10: >>> def add(x,y): return x+y... >>> reduce(add, range(1, 11)) 55 If there's only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.If there's only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.

20 COMP 144 Programming Language Concepts Felix Hernandez-Campos Reduce A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on.A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example,For example, >>> def sum(seq):... def add(x,y): return x+y... return reduce(add, seq, 0)... >>> sum(range(1, 11)) 55 >>> sum([]) 0

21 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lambda Abstractions Anonymous functions are also usefulAnonymous functions are also useful –They are known as lambda abstractions HaskellHaskell map (\x->3*x) [1,2,3] PythonPython >>> car = lambda lst: lst[0] >>> cdr = lambda lst: lst[1:] >>> sum2 = lambda lst: car(lst)+car(cdr(lst)) >>> sum2(range(10)) 1

22 COMP 144 Programming Language Concepts Felix Hernandez-Campos More on Python Functional Programming Articles by David MertzArticles by David Mertz ibm.com/developerworks/linux/library/l- prog.htmlhttp://www- 106.ibm.com/developerworks/linux/library/l- prog.htmlhttp://www- 106.ibm.com/developerworks/linux/library/l- prog.htmlhttp://www- 106.ibm.com/developerworks/linux/library/l- prog.html prog2.htmlhttp://www-106.ibm.com/developerworks/library/l- prog2.htmlhttp://www-106.ibm.com/developerworks/library/l- prog2.htmlhttp://www-106.ibm.com/developerworks/library/l- prog2.html

23 COMP 144 Programming Language Concepts Felix Hernandez-Campos Reading Assignment Python tutorialPython tutorial –List comprehensions » http:// –List displays » –Higher-order programming with list » http://