Slides Cours10 Functional Programming
Slides Cours10 Functional Programming
2023-12-07
You’ve already met functional programming in Python!
Code that is easier to reason about (shorter, clarity…)
Improved uncoupling of code
Better handling of concurrency
Why functional programming?
Code that is easier to reason about (shorter, clarity…)
Functional interfaces
Improved uncoupling of code
Lambda expressions
Better handling of concurrency
Stream API
Nesting classes
A basic spreadsheet
A basic spreadsheet
Spreadsheet document
Spreadsheet document
This is the
“outer” class
Static nested classes: Bring class closer to method
This is the
“outer” class
“RowComparator2” has access to the private
static members of Spreadsheet
(enumerations, helpers...)
Static nested classes: Bring class closer to method
This is the
“outer” class
“RowComparator2” has access to the private
static members of Spreadsheet
(enumerations, helpers...)
This is the
“outer” class
“RowComparator2” has access to the private
static members of Spreadsheet
(enumerations, helpers...)
No need to copy
“sortOnColumn”
anymore!
Inner classes: Give access to non-static members
No need to copy
“sortOnColumn”
anymore!
Syntactic sugar
Syntactic sugar
Java compiler
Syntactic sugar
Java compiler
Syntactic sugar
Java compiler
Syntactic sugar
Java compiler
Inner and anonymous classes have access to the variables of their method!
A functional interface is defined as an interface that contains only one abstract method
Functional interfaces are also known as Single Abstract Method (SAM) interfaces
The interfaces Comparator<T>, ActionListener, Runnable, and Callable<T>
are all examples of functional interfaces
Functional interfaces are a key component of functional programming support
introduced in Java 8
Lambda expressions
Name of the
arguments
Lambda expressions
Comparator<T>
ActionListener
Runnable
General form of a lambda expression
General form of a lambda expression
Possible simplifications:
The compiler can generally infer the type of the arguments:
(a, b, c /*...*/) -> { /*...*/ }
If one argument: a -> { /*...*/ }
If no body: (a, b, c /*...*/) -> /* result */
If no return: (a, b, c /*...*/) -> /* body */
General form of a lambda expression
General-purpose classes that provide a context to create and hold lambda expressions:
Unary functions: Function<T,R>
Binary functions: BiFunction<T,U,R>
Unary operators: UnaryOperator<T>
Binary operators: BinaryOperator<T>
Predicates: Predicate<T>
Consumers: Consumer<T>
...
Unary functions
Example 1
Example 2
Binary functions
Operators: Functions with one type
Predicates: Functions returning a Boolean
Consumers: Functions producing no result
Composition of functions or operators
Composition of predicates
Higher-order functions