Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Examples C Pascal Unix (sh) Object-Oriented Deal with collections of objects which maintain internal state and support methods that query or modify this internal state in some way. Examples Java Smalltalk Functional Decomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state. Examples Haskell OCaml ML Declarative Specification describes the problem to be solved, and language implementation figures out the details Examples SQL Prolog
146
Embed
Programming Paradigms - Personepages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonFP.pdfProgramming Paradigms Procedural Sequence of instructions that inform the computer what
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Programming ParadigmsProcedural
Sequence of instructions that inform the computer what to do with the program's input
ExamplesC
PascalUnix (sh)
Object-Oriented Deal with collections of objects which maintain internal
state and support methods that query or modify this internal state in some way.
ExamplesJava
Smalltalk
FunctionalDecomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state.
ExamplesHaskellOCaml
ML
Declarative Specification describes the problem to be solved, and
language implementation figures out the details
ExamplesSQL
Prolog
Programming ParadigmsProcedural
Sequence of instructions that inform the computer what to do with the program's input
ExamplesC
PascalUnix (sh)
Object-Oriented Deal with collections of objects which maintain internal
state and support methods that query or modify this internal state in some way.
ExamplesJava
Smalltalk
FunctionalDecomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state.
ExamplesHaskellOCaml
ML
Declarative Specification describes the problem to be solved, and
language implementation figures out the details
ExamplesSQL
Prolog
Multi-Paradigm Supports several different
paradigms, to be combined freely
ExamplesScalaC++
Python
Functional Programming Concepts
Primary entity is a "function"
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input No side effects that modify internal state
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input No side effects that modify internal state print() and file.write() are side effects
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input No side effects that modify internal state print() and file.write() are side effectsStrict (Haskell): no assignments, variables, or state
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input No side effects that modify internal state print() and file.write() are side effectsStrict (Haskell): no assignments, variables, or stateFlexible (Python): encourage low-interference functions
Functional Programming Concepts
Primary entity is a "function""Pure" functions are mathematical Output depends only on input No side effects that modify internal state print() and file.write() are side effectsStrict (Haskell): no assignments, variables, or stateFlexible (Python): encourage low-interference functions Functional-looking interface but use variables, state internally
Functional Programming Concepts
Why Functional Programming?
Why avoid objects and side effects?
Why Functional Programming?
Why avoid objects and side effects?Formal Provability Line-by-line invariants
Why Functional Programming?
Why avoid objects and side effects?Formal Provability Line-by-line invariantsModularity Encourages small independent functions
Why Functional Programming?
Why avoid objects and side effects?Formal Provability Line-by-line invariantsModularity Encourages small independent functionsComposability Arrange existing functions for new goals
Why Functional Programming?
Why avoid objects and side effects?Formal Provability Line-by-line invariantsModularity Encourages small independent functionsComposability Arrange existing functions for new goalsEasy Debugging Behavior depends only on input
Why Functional Programming?
Why avoid objects and side effects?Formal Provability Line-by-line invariantsModularity Encourages small independent functionsComposability Arrange existing functions for new goalsEasy Debugging Behavior depends only on input
Let's Get Started!
Why Functional Programming?
Map / Filter
Common Pattern
output = [] for element in iterable: val = function(element) output.append(val) return output
Common Pattern
output = [] for element in iterable: val = function(element) output.append(val) return output
return [function(element) for element in iterable]
Common Pattern
output = [] for element in iterable: val = function(element) output.append(val) return output
return [function(element) for element in iterable]
Common Pattern
output = [] for element in iterable: val = function(element) output.append(val) return output
return [function(element) for element in iterable]
Common Pattern
[len(s) for s in languages]["python", "perl", "java", "c++"]
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
6
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
6
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
46
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
46
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4
len
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4 3
len
[ , , , ]
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4 3
len
[ , , , ]
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4 3
lenApply some function to every element of a sequence
map(fn, iter)
No discussion of elements!
map :: (a -> b) x [a] -> [b]
< , , , >
[len(s) for s in languages]["python", "perl", "java", "c++"]
46 4 3
map(len, languages)
Another Common Pattern
output = [] for element in iterable: if predicate(element): output.append(val) return output
Another Common Pattern
output = [] for element in iterable: if predicate(element): output.append(val) return output
[element for element in iterable if predicate(element)]
Another Common Pattern
output = [] for element in iterable: if predicate(element): output.append(val) return output
[element for element in iterable if predicate(element)]
Another Common Pattern
output = [] for element in iterable: if predicate(element): output.append(val) return output
[element for element in iterable if predicate(element)]
Another Common Pattern
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
2
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
2
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
2
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82
is_even
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82 34
is_even
[ , , ]
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82 34
is_even
[ , , ]
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82 34
is_even Only keep elements that satisfy some predicate
filter(pred, iter)
No discussion of elements!
filter :: (a -> bool) x [a] -> [a]
< , , >
[num for num in fibs if is_even(num)]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
82 34
filter(is_even, fibs)
Lambda Functions
Anonymous, on-the-fly, unnamed functions
Lambda Functions
lambda params: expr(params)Returns an expression
Keyword lambda creates an anonymous function
Defined Functions vs. Lambdas
def greet(): print("Hi!")
Defined Functions vs. Lambdasdef binds a function object
to a namefunction
bytecode
greet
greet
def greet(): print("Hi!")
lambda val: val ** 2lambda x, y: x * ylambda pair: pair[0] * pair[1]
Defined Functions vs. Lambdasdef binds a function object
to a name
lambda only creates a function object
function
bytecode
<lambda>
function
bytecode
greet
greet
def greet(): print("Hi!")
lambda val: val ** 2lambda x, y: x * ylambda pair: pair[0] * pair[1]
(lambda x: x > 3)(4) # => True
Defined Functions vs. Lambdasdef binds a function object
to a name
lambda only creates a function object
function
bytecode
<lambda>
function
bytecode
greet
greet
Using Lambdas
triple = lambda x: x * 3 # NEVER EVER DO THIS
Using Lambdas
triple = lambda x: x * 3 # NEVER EVER DO THIS
# Squares from 0**2 to 9**2map(lambda val: val ** 2, range(10))
Using Lambdas
triple = lambda x: x * 3 # NEVER EVER DO THIS
# Squares from 0**2 to 9**2map(lambda val: val ** 2, range(10))
# Tuples with positive second elementsfilter(lambda pair: pair[1] > 0, [(4,1), (3, -2), (8,0)]
Using Lambdas
Iterators and Generators
Represent data stream, returned one element at a time
Iterators
Iterators
Iterators are objects, like (almost) everything in PythonRepresent finite or infinite data streams
Iterators
Iterators are objects, like (almost) everything in PythonRepresent finite or infinite data streams
Use next(iterator) to yield successive values Raises StopIteration error upon termination
Iterators
Iterators are objects, like (almost) everything in PythonRepresent finite or infinite data streams
Use next(iterator) to yield successive values Raises StopIteration error upon terminationUse iter(data) to build an iterator for a data structure
Iterators
Iterable
# Build an iterator over [1,2,3]it = iter([1,2,3])
Iterable
# Build an iterator over [1,2,3]it = iter([1,2,3])
next(it) # => 1
Iterable
# Build an iterator over [1,2,3]it = iter([1,2,3])
next(it) # => 1next(it) # => 2
Iterable
# Build an iterator over [1,2,3]it = iter([1,2,3])
next(it) # => 1next(it) # => 2next(it) # => 3
Iterable
# Build an iterator over [1,2,3]it = iter([1,2,3])
def fibs_under(n): for f in generate_fibs(): # Loops over 1, 1, 2, … if f > n: break print(f)
Lazy Generation
Summary: Why Use Iterators and Generators?
Compute data on demand Reduces in-memory buffering Can avoid expensive function calls
Summary: Why Use Iterators and Generators?
Compute data on demand Reduces in-memory buffering Can avoid expensive function callsrange, map, filter and others are iterable
Summary: Why Use Iterators and Generators?
Compute data on demand Reduces in-memory buffering Can avoid expensive function callsrange, map, filter and others are iterableGreat for asynchronous programming (network/web)