SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Functional OO
Programming
Prof. Dr. Ralf Lämmel
Universität Koblenz-Landau
Software Languages Team
Let’s say we know OOP.
What’s functional programming?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Functional programming focuses on
functions as abstractions (as in math).
-- Two functions only requiring zero, succ, pred
add n m = if (n==0) then m else (add (n-1) m) + 1
mult n m = if (n==0) then 0 else add (mult (n-1) m) m
Functions are perfectly well-defined mathematical entities.
Making us think of the above functions as objects isn’t that helpful.
Haskell
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Encoding functions as instance methods
To be void or to return?
Why to tie a function to the class for the 1st argument?
public class “int” {
public int add(int m) {
return (this==0) ? m : (this-1).add(m)+1;
}
public int mult(int m) {
return (this==0) ? 0 : (this-1).mult(m). add(m);
}
}
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
public class TrivialExample {
public static int add(int n, int m) {
return (n==0) ? m : add(n-1,m)+1;
}
public static int mult(int n, int m) {
return (n==0) ? 0 : add(mult(n-1,m),m);
}
}
What’s the purpose of classes here?
There is some boilerplate code.
Encoding functions as static methods
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
evaluate :: Expr -> Int
evaluate (Lit i) = i
evaluate (Add l r) = evaluate l + evaluate r
Remember the expression problem!
Virtual functions scatter the code over classes.
Haskell
Functional programming supports
case discrimination.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Instance-of-based pattern matching
public static int Evaluate(Expr e) {
if (e instanceof Lit) {
Lit l = (Lit)e;
return l.info;
}
if (e instanceof Add) {
Add a = (Add)e;
return Evaluate(a.left) + Evaluate(a.right);
}
throw new IllegalArgumentException();
}
Very little type checking!
Proper functional OO programming instances to the rescue.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
filter is a higher-order function!
-- QuickSort in Haskell
quicksort [] = []
quicksort [e] = [e]
quicksort unsorted = quicksort lt ++ eq ++ quicksort gt
where
pivot = head unsorted
lt = filter (<pivot) unsorted
eq = filter (==pivot) unsorted
gt = filter (>pivot) unsorted
Haskell
Functional programming encourages
composition of functionality
via higher-order functions.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
We iterate the increment function forever.
However, we only take the first 5 elements of the stream.
> take 5 (iterate (1+) 0)
[0,1,2,3,4]
Haskell
Functional programming supports
(in some instances) lazy evaluation.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Hence:
• Optimizations can be more aggressive.
• Parallelization is feasible more often.
• Transactions in memory are more manageable.
• Proofs of program correctness rely on referential transparency.
Functional programming encourages
pure functions.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
(define (memoize f)
(let ((table (make-table)))
(lambda (x)
(let ((previously-computed-result (lookup x table)))
(if (not (null? previously-computed-result))
previously-computed-result
(let ((result (f x)))
(insert! x result table)
result))))))
A memoization function as of Brian Goetz: Java theory and practice: The
closures debate, 2007, IBM developerWorks.
The combinator takes a function and returns a function.
It interleaves imperative actions with normal function application.
Scheme
Functional programming supports
composition of closures.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The notion of closure
Wikipedia as of 4 June 2013: In computer science, a closure
(also lexical closure or function closure) is a function or
reference to a function together with a referencing
environment—a table storing a reference to each of the non-
local variables (also called free variables) of that function. [...]
The concept of closures was developed in the 1960s and
was first fully implemented in 1975 [...] as a language feature
in the Scheme programming language to support lexically
scoped first-class functions.
What’s functional OO
programming (in Java 7)?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Functional OO Programming
in Java 7
Relevant Java concepts
Nested classes
Anonymous classes
Function objects (functors)
Riddles
Can we do filter in Java 7 (or C#)?
Can we be lazy in Java 7 (or C#)?
Can we do memoization in Java 7 (or C#)?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Nested classes in Java
class OuterClass {
! ...
! class NestedClass { ... }
! ...
}
• Nested classes can be class members.
• Nested classes can be declared locally in a method.
• Non-static nested classes have access to outer scope.
• Why use nested classes?
– Group classes that are only used in one place.
– Nested scopes – simulate closures.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Anonymous classes
cutButton.addActionListener(
	 new ActionListener() {
	 	 public void actionPerformed(ActionEvent e) {
	 	 	 controller.cutEmployeeClicked();
	 	 }
	 });
• These are nested classes w/o a name.
• They are derived from an interface or base class.
• Members are declared as part of construction.
• Free names occur inside the constructor.
A closure
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Closures in Java
In Java (7), we may equate the notion of an
anonymous class with (a restricted form of) the
general notion of closure. For such a closure to
be “nontrivial” (in the sense that the
anonymous class cannot be trivially eliminated),
the anonymous class should reference
“variables” outside the immediate scope of the
anonymous class. For instance, there could be
references to the arguments of the enclosing
method, or to temporary variables, or to fields
of the hosting object. (By the language rules, the
variables are all “final”.)
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Listeners in a GUI
DEMO
cutButton.addActionListener(
	 new ActionListener() {
	 	 public void actionPerformed(ActionEvent e) {
	 	 	 controller.cutEmployeeClicked();
	 	 }
	 });
101implementation:swing
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Function objects
Wikipedia as of 4 June 2013: “A function object [...]
is a computer programming construct allowing an
object to be invoked or called as if it were an
ordinary function, usually with the same syntax (a
function parameter that can also be a function).”
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Sample of a functor interface
/**
* Functions with 1 argument
*/
public interface UnaryFunction<X,Y> {
	 public Y apply(X x);
}
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Sample of a functor implementation
twice(
	 new UnaryFunction<Integer,Integer>(){
	 	 public Integer apply(Integer x) {
	 	 	 return ++x;
	 	 }
	 },
40
)
Exercise: suppose this expression is
supposed to compute 42 because twice
applies the argument twice. What’s the
definition of twice?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Issues with Java <= 7 functors
Only function objects – no functions.
Verbose creation of closures.
No access to non-final variables in outer scope.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Further reading
• John Hughes: Why Functional Programming Matters, 1989,
Computer Journal, available online.
• Alexandre Pereira Calsavara: Achieve better Java code with
inner and anonymous classes, 2003, TechRepublic, available
online.
• Abhijit Belapurkar: Functional programming in the Java
language, 2004, IBM developerWorks, available online.
Major use case for FOOP:
Combinator libraries
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The notion of
combinator library
Wikipedia as of 4 June 2013: “A combinator library is a
software library which implements combinators for a
functional programming language; "the key idea is this: a
combinator library offers functions (the combinators) that
combine functions together to make bigger functions". [...]
These kinds of libraries are particularly useful for
allowing domain-specific programming languages to be
easily embedded into a general purpose language [...].“
Traversal
combinators
http://101companies.org/wiki/
Contribution:javaSyb
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Motivation of
traversal combinators
public static void cut(Company c) {
		 Walker w = new Walker(c);
		 for (Object o : w)
		 	 if (o instanceof Employee) {
		 	 	 Employee e = (Employee)o;
		 	 	 e.setSalary(e.getSalary() / 2);
		 	 }
}
http://101companies.org/wiki/Contribution:javaReflection
How to be more
typeful?
What other traversals
are conceivable?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Motivation of
traversal combinators
public static Double total(Company c) {
	 	 Walker w = new Walker(c);
	 	 double result = 0;
	 	 for (Object o : w)
	 	 	 if (o instanceof Employee) {
	 	 	 	 Employee e = (Employee)o;
	 	 	 	 result += e.getSalary();
	 	 	 }
	 	 return result;
}
http://101companies.org/wiki/Contribution:javaReflection
How to be more
typeful?
What other traversals
are conceivable?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The paradigm of using
traversal combinators
Identify problem-specific ingredients:
Type-specific actions or functions.
Represent these ingredients as closures.
Extend those ingredients into generic ones.
Apply a traversal scheme.
Such schemes are closure combinators.
Specifically,w
e
useSYB
style.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Problem-specific transformation
functionality for “Cut”
public static Action<Employee> updateSalary() {
return new Action<Employee>() {
public void apply(Employee x) {
x.setSalary(x.getSalary() / 2);
}
};
}
Update the salary when facing
an employee along traversal
http://101companies.org/wiki/Contribution:javaSyb
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Problem-specific query
functionality for “Total”
public static Function<Employee,Double> getSalary() {
return new Function<Employee, Double>() {
public Double apply(Employee x) {
return x.getSalary();
}
};
}
Extract the salary when facing an
employee along traversal
http://101companies.org/wiki/Contribution:javaSyb
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Combine type-specific transformation
with identity function
public static <X> Action<Object> orIdentity(final Action<X> a) {
return new Action<Object>() {
public void apply(Object x) {
try { a.apply((X)x); }
catch (ClassCastException _) { }
}
};
}
Rely on cast exception to
check for applicability of
type-specific case
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Combine type-specific query with
constant function
public static <X,Y> Function<Object,Y> orDefault(
	 	 	 	 	 	 	 	 final Function<X,Y> f,
	 	 	 	 	 	 	 	 final Y otherwise) {
return or(f, new Function<Object,Y>() {
	 	 	 	 	 	 	 public Y apply(Object x) { return otherwise; }
	 	 	 	 	 	 });
}
or uses cast in the same
way as orIdentity.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Apply traversal scheme for
transformation
public static void cut(Company c) {
everywhere(orIdentity(updateSalary())).apply(c);
}
Try out every node
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Apply traversal scheme for query
public static Double total(Company c) {
return everything(
orDefault(getSalary(), 0.0),
add,
0.0).apply(c);
}
Try out
every node
Add intermediate
results
Start from
“0.0”
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The traversal scheme
everywhere
public static Action<Object> everywhere(
	 	 	 	 	 	 	 	 final Action<Object> a) {
return new Action<Object>() {
public void apply(Object x) {
all(everywhere(a)).apply(x);
a.apply(x);
}
};
}
Compose an action which applies argument
action a to all the subobjects reachable from
the object passed to the composed action.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The traversal scheme
everywhere
public static Action<Object> everywhere(
	 	 	 	 	 	 	 	 final Action<Object> a) {
return new Action<Object>() {
public void apply(Object x) {
all(everywhere(a)).apply(x);
a.apply(x);
}
};
}
Recurse into all
immediate subobjects
using reflection
Apply the action
to the last
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The traversal scheme
everything
public static <Y> Function<Object,Y> everything(
	 	 	 	 	 	 	 	 	 	 final Function<Object,Y> f,
	 	 	 	 	 	 	 	 	 	 final BinaryOperator<Y> op,
	 	 	 	 	 	 	 	 	 	 final Y initial) {
return new Function<Object,Y>() {
public Y apply(Object x) {
return op.apply(f.apply(x),
	 	 	 	 	 	 	 	 	 	 all(	everything(f, op, initial),
	 	 	 	 	 	 	 	 	 	 	 	 op,
	 	 	 	 	 	 	 	 	 	 	 	 initial).apply(x));
}
};
}
Compose a function which applies argument
function f to all the subobjects reachable while
composing intermediate results with the binary
operator op while starting from initial.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The traversal scheme
everything
public static <Y> Function<Object,Y> everything(
	 	 	 	 	 	 	 	 	 	 final Function<Object,Y> f,
	 	 	 	 	 	 	 	 	 	 final BinaryOperator<Y> op,
	 	 	 	 	 	 	 	 	 	 final Y initial) {
return new Function<Object,Y>() {
public Y apply(Object x) {
return op.apply(f.apply(x),
	 	 	 	 	 	 	 	 	 	 all(	everything(f, op, initial),
	 	 	 	 	 	 	 	 	 	 	 	 op,
	 	 	 	 	 	 	 	 	 	 	 	 initial).apply(x));
}
};
}
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Traversal of companies
DEMO
http://101companies.org/wiki/
Contribution:javaSyb
Parser
combinators
http://101companies.org/wiki/
Contribution:javaParseLib
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
	 void department() {
	 	 match(DEPARTMENT);
	 	 match(STRING);
	 	 match(OPEN);
	 	 match(MANAGER);
	 	 employee();
	 	 while (test(EMPLOYEE)) {
	 	 	 match(EMPLOYEE);
	 	 	 employee();
	 	 }
	 	 while (test(DEPARTMENT))
	 	 	 department();
	 	 match(CLOSE);
	 }
department :
'department' STRING '{'
('manager' employee)
('employee' employee)*
dept*
'}';
Grammar
production
Corresponding
procedure
Motivation: how to avoid encoding
of recursive descent parsing?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The paradigm of using
parser combinators
Model functor classes for acceptance & parsing.
Model closure combinators for EBNF constructs.
Sequence, Choice, Star, Plus, ...
Model nonterminals as closure-returning methods.
Encode RHS of productions in method body.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
The types of
acceptors and parsers
public abstract class Acceptor {
	 public abstract boolean accept(Input i);
}
public abstract class Parser<T> {
	 public abstract T parse(Input i);
}
Abstract
functor
classes
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
An acceptor combinator for “*”
public class Star extends Acceptor {
	 private Acceptor a;
	 public Star(Acceptor a) { this.a = a; }
	 public boolean accept(Input i) {
	 	 while (true) {
	 	 	 int mark = i.getPos();
	 	 	 if (!a.accept(i)) {
	 	 	 	 i.setPos(mark);
	 	 	 	 return true;
	 	 	 }
	 	 }	 	
	 }
}
Accept input from i for as many times as possible.
Make sure not to consume input that was seen
when i was finally failing. (Backtracking needed.)
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
An acceptor combinator for “*”
public class Star extends Acceptor {
	 private Acceptor a;
	 public Star(Acceptor a) { this.a = a; }
	 public boolean accept(Input i) {
	 	 while (true) {
	 	 	 int mark = i.getPos();
	 	 	 if (!a.accept(i)) {
	 	 	 	 i.setPos(mark);
	 	 	 	 return true;
	 	 	 }
	 	 }	 	
	 }
}
Concrete
functor
class
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
	 public static Acceptor star(final Acceptor a) {
	 	 return new Acceptor() {
	 	 	 public boolean accept(Input i) {
	 	 	 	 while (true) {
	 	 	 	 	 int mark = i.getPos();
	 	 	 	 	 if (!a.accept(i)) {
	 	 	 	 	 	 i.setPos(mark);
	 	 	 	 	 	 return true;
	 	 	 	 	 }
	 	 	 	 }	 	
	 	 	 }
	 	 };
	 }
An alternative:
a static function
that returns a
closure
An acceptor combinator for “*”
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
public class Star<T> extends Parser<List<T>> {
	 private Parser<T> p;
	 public Star(Parser<T> p) { this.p = p; }
	 public List<T> parse(Input i) {
	 	 List<T> r = new LinkedList<T>();
	 	 while (true) {
	 	 	 int mark = i.getPos();
	 	 	 T t = p.parse(i);
	 	 	 if (t!=null)
	 	 	 	 r.add(t);
	 	 	 else {
	 	 	 	 i.setPos(mark);
	 	 	 	 return r;
	 	 	 }
	 	 }	 	
	 }
}
An parser combinator for “*”
Given a parser p which returns a T, construct a
parser which returns a list of Ts.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
public class Star<T> extends Parser<List<T>> {
	 private Parser<T> p;
	 public Star(Parser<T> p) { this.p = p; }
	 public List<T> parse(Input i) {
	 	 List<T> r = new LinkedList<T>();
	 	 while (true) {
	 	 	 int mark = i.getPos();
	 	 	 T t = p.parse(i);
	 	 	 if (t!=null)
	 	 	 	 r.add(t);
	 	 	 else {
	 	 	 	 i.setPos(mark);
	 	 	 	 return r;
	 	 	 }
	 	 }	 	
	 }
}
Concrete
functor
class
An parser combinator for “*”
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
EBNF of 101companies
company :
'company' STRING '{' department* '}' EOF;
department :
'department' STRING '{'
('manager' employee)
('employee' employee)*
department*
'}';
employee :
STRING '{'
'address' STRING
'salary' FLOAT
'}';
STRING : '"' (~'"')* '"';
FLOAT : ('0'..'9')+ ('.' ('0'..'9')+)?;
Let’s parse
companies
again.
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Nonterminals as static fields
	 public static final Acceptor STRING =
	 	 WS(sequence(
	 	 	 	 CHAR('"'),
	 	 	 	 star(sequence(not(CHAR('"')),any)),
	 	 	 	 CHAR('"')));
STRING : '"' (~'"')* '"';
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Nonterminals as methods
	 public static Acceptor department() {
	 	 return new Acceptor() {
	 	 	 public boolean accept(Input i) {
	 	 	 	 return (
	 	 	 	 	 	 sequence(
	 	 	 	 	 	 	 SPECIAL("department"),
	 	 	 	 	 	 	 STRING,
	 	 	 	 	 	 	 SPECIAL("{"),
	 	 	 	 	 	 	 employee("manager"),
	 	 	 	 	 	 	 star(employee("employee")),
	 	 	 	 	 	 	 star(department()),
	 	 	 	 	 	 	 SPECIAL("}")
	 	 	 	 	 	 )).accept(i);
	 	 	 }
	 	 };
	 }
department :
'department' STRING '{'
('manager' employee)
('employee' employee)*
department*
'}';
What’s the limit of
“nonterminals as
static fields”?
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Parsing comapanies
DEMO
http://101companies.org/wiki/
Contribution:javaParseLib
(C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable)
Summary
Functional OOP really combines OOP and FP:
OOP: Encapsulation and generalization
FP: Function application, composition, combination
Major use case for FOOP: combinator libraries.
There are languages more suitable for functional OOP:
Java 8, F#, C#, Ruby, Python, ...

Weitere ähnliche Inhalte

Was ist angesagt?

Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypse
elliando dias
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
Tech_MX
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
Ranel Padon
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
Martin Odersky
 

Was ist angesagt? (20)

Enriching Your Models with OCL
Enriching Your Models with OCLEnriching Your Models with OCL
Enriching Your Models with OCL
 
Applicative Logic Meta-Programming as the foundation for Template-based Progr...
Applicative Logic Meta-Programming as the foundation for Template-based Progr...Applicative Logic Meta-Programming as the foundation for Template-based Progr...
Applicative Logic Meta-Programming as the foundation for Template-based Progr...
 
Stay fresh
Stay freshStay fresh
Stay fresh
 
Clojure and The Robot Apocalypse
Clojure and The Robot ApocalypseClojure and The Robot Apocalypse
Clojure and The Robot Apocalypse
 
Enrich Your Models With OCL
Enrich Your Models With OCLEnrich Your Models With OCL
Enrich Your Models With OCL
 
C++ first s lide
C++ first s lideC++ first s lide
C++ first s lide
 
14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
 
Python Programming - III. Controlling the Flow
Python Programming - III. Controlling the FlowPython Programming - III. Controlling the Flow
Python Programming - III. Controlling the Flow
 
Erlang, an overview
Erlang, an overviewErlang, an overview
Erlang, an overview
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
flatMap Oslo presentation slides
flatMap Oslo presentation slidesflatMap Oslo presentation slides
flatMap Oslo presentation slides
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 
C++ to java
C++ to javaC++ to java
C++ to java
 

Andere mochten auch

Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Ralf Laemmel
 
Modeling software systems at a macroscopic scale
Modeling software systems  at a macroscopic scaleModeling software systems  at a macroscopic scale
Modeling software systems at a macroscopic scale
Ralf Laemmel
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)
Ralf Laemmel
 
Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)
Ralf Laemmel
 
An introduction on language processing
An introduction on language processingAn introduction on language processing
An introduction on language processing
Ralf Laemmel
 
Healthy eating tania santoro iic s.u.
Healthy eating    tania santoro iic s.u.Healthy eating    tania santoro iic s.u.
Healthy eating tania santoro iic s.u.
Valentina Mariano
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)
Ralf Laemmel
 
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Ralf Laemmel
 

Andere mochten auch (20)

Iphone6
Iphone6Iphone6
Iphone6
 
Descubriendo Facebook
Descubriendo FacebookDescubriendo Facebook
Descubriendo Facebook
 
diapositivas
diapositivas diapositivas
diapositivas
 
Mobilna edukacja - jak wykorzystać potencjał edukacyjny nowoczesnych telefonó...
Mobilna edukacja - jak wykorzystać potencjał edukacyjny nowoczesnych telefonó...Mobilna edukacja - jak wykorzystać potencjał edukacyjny nowoczesnych telefonó...
Mobilna edukacja - jak wykorzystać potencjał edukacyjny nowoczesnych telefonó...
 
Vida de jesus
Vida de jesusVida de jesus
Vida de jesus
 
To upload
To uploadTo upload
To upload
 
The Apache Way
The Apache WayThe Apache Way
The Apache Way
 
Polinomios 3eso
Polinomios 3esoPolinomios 3eso
Polinomios 3eso
 
Focus BNL #37
Focus BNL #37Focus BNL #37
Focus BNL #37
 
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
Surfacing ‘101’ in a Linked Data manner as presented at SATToSE 2013
 
Modeling software systems at a macroscopic scale
Modeling software systems  at a macroscopic scaleModeling software systems  at a macroscopic scale
Modeling software systems at a macroscopic scale
 
Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)Remote method invocation (as part of the the PTT lecture)
Remote method invocation (as part of the the PTT lecture)
 
Facing communication challenges in collaborative development
Facing communication challenges in collaborative developmentFacing communication challenges in collaborative development
Facing communication challenges in collaborative development
 
Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)Database programming including O/R mapping (as part of the the PTT lecture)
Database programming including O/R mapping (as part of the the PTT lecture)
 
A STUDY OF THE ISSUES AND SECURITY OF CLOUD COMPUTING
A STUDY OF THE ISSUES AND SECURITY OF CLOUD COMPUTINGA STUDY OF THE ISSUES AND SECURITY OF CLOUD COMPUTING
A STUDY OF THE ISSUES AND SECURITY OF CLOUD COMPUTING
 
An introduction on language processing
An introduction on language processingAn introduction on language processing
An introduction on language processing
 
Healthy eating tania santoro iic s.u.
Healthy eating    tania santoro iic s.u.Healthy eating    tania santoro iic s.u.
Healthy eating tania santoro iic s.u.
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structures
 
Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)Multithreaded programming (as part of the the PTT lecture)
Multithreaded programming (as part of the the PTT lecture)
 
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
Aspect-oriented programming with AspectJ (as part of the the PTT lecture)
 

Ähnlich wie Functional OO programming (as part of the the PTT lecture)

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
Ralf Laemmel
 
Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)
Ralf Laemmel
 
Language processing patterns
Language processing patternsLanguage processing patterns
Language processing patterns
Ralf Laemmel
 
The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)
Ralf Laemmel
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
SahajShrimal1
 

Ähnlich wie Functional OO programming (as part of the the PTT lecture) (20)

LISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love ParanthesesLISP: How I Learned To Stop Worrying And Love Parantheses
LISP: How I Learned To Stop Worrying And Love Parantheses
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Generative programming (mostly parser generation)
Generative programming (mostly parser generation)Generative programming (mostly parser generation)
Generative programming (mostly parser generation)
 
ScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
 
Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)Selected design patterns (as part of the the PTT lecture)
Selected design patterns (as part of the the PTT lecture)
 
Language processing patterns
Language processing patternsLanguage processing patterns
Language processing patterns
 
Javascript
JavascriptJavascript
Javascript
 
The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)The Expression Problem (as part of the the PTT lecture)
The Expression Problem (as part of the the PTT lecture)
 
Presentation
PresentationPresentation
Presentation
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
 
Introduction to Clojure
Introduction to ClojureIntroduction to Clojure
Introduction to Clojure
 
Knowledge of Javascript
Knowledge of JavascriptKnowledge of Javascript
Knowledge of Javascript
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 

Functional OO programming (as part of the the PTT lecture)

  • 1. Functional OO Programming Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team
  • 2. Let’s say we know OOP. What’s functional programming?
  • 3. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Functional programming focuses on functions as abstractions (as in math). -- Two functions only requiring zero, succ, pred add n m = if (n==0) then m else (add (n-1) m) + 1 mult n m = if (n==0) then 0 else add (mult (n-1) m) m Functions are perfectly well-defined mathematical entities. Making us think of the above functions as objects isn’t that helpful. Haskell
  • 4. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Encoding functions as instance methods To be void or to return? Why to tie a function to the class for the 1st argument? public class “int” { public int add(int m) { return (this==0) ? m : (this-1).add(m)+1; } public int mult(int m) { return (this==0) ? 0 : (this-1).mult(m). add(m); } }
  • 5. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) public class TrivialExample { public static int add(int n, int m) { return (n==0) ? m : add(n-1,m)+1; } public static int mult(int n, int m) { return (n==0) ? 0 : add(mult(n-1,m),m); } } What’s the purpose of classes here? There is some boilerplate code. Encoding functions as static methods
  • 6. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) evaluate :: Expr -> Int evaluate (Lit i) = i evaluate (Add l r) = evaluate l + evaluate r Remember the expression problem! Virtual functions scatter the code over classes. Haskell Functional programming supports case discrimination.
  • 7. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Instance-of-based pattern matching public static int Evaluate(Expr e) { if (e instanceof Lit) { Lit l = (Lit)e; return l.info; } if (e instanceof Add) { Add a = (Add)e; return Evaluate(a.left) + Evaluate(a.right); } throw new IllegalArgumentException(); } Very little type checking! Proper functional OO programming instances to the rescue.
  • 8. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) filter is a higher-order function! -- QuickSort in Haskell quicksort [] = [] quicksort [e] = [e] quicksort unsorted = quicksort lt ++ eq ++ quicksort gt where pivot = head unsorted lt = filter (<pivot) unsorted eq = filter (==pivot) unsorted gt = filter (>pivot) unsorted Haskell Functional programming encourages composition of functionality via higher-order functions.
  • 9. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) We iterate the increment function forever. However, we only take the first 5 elements of the stream. > take 5 (iterate (1+) 0) [0,1,2,3,4] Haskell Functional programming supports (in some instances) lazy evaluation.
  • 10. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Hence: • Optimizations can be more aggressive. • Parallelization is feasible more often. • Transactions in memory are more manageable. • Proofs of program correctness rely on referential transparency. Functional programming encourages pure functions.
  • 11. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) (define (memoize f) (let ((table (make-table))) (lambda (x) (let ((previously-computed-result (lookup x table))) (if (not (null? previously-computed-result)) previously-computed-result (let ((result (f x))) (insert! x result table) result)))))) A memoization function as of Brian Goetz: Java theory and practice: The closures debate, 2007, IBM developerWorks. The combinator takes a function and returns a function. It interleaves imperative actions with normal function application. Scheme Functional programming supports composition of closures.
  • 12. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The notion of closure Wikipedia as of 4 June 2013: In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non- local variables (also called free variables) of that function. [...] The concept of closures was developed in the 1960s and was first fully implemented in 1975 [...] as a language feature in the Scheme programming language to support lexically scoped first-class functions.
  • 14. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Functional OO Programming in Java 7 Relevant Java concepts Nested classes Anonymous classes Function objects (functors) Riddles Can we do filter in Java 7 (or C#)? Can we be lazy in Java 7 (or C#)? Can we do memoization in Java 7 (or C#)?
  • 15. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Nested classes in Java class OuterClass { ! ... ! class NestedClass { ... } ! ... } • Nested classes can be class members. • Nested classes can be declared locally in a method. • Non-static nested classes have access to outer scope. • Why use nested classes? – Group classes that are only used in one place. – Nested scopes – simulate closures.
  • 16. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Anonymous classes cutButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { controller.cutEmployeeClicked(); } }); • These are nested classes w/o a name. • They are derived from an interface or base class. • Members are declared as part of construction. • Free names occur inside the constructor. A closure
  • 17. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Closures in Java In Java (7), we may equate the notion of an anonymous class with (a restricted form of) the general notion of closure. For such a closure to be “nontrivial” (in the sense that the anonymous class cannot be trivially eliminated), the anonymous class should reference “variables” outside the immediate scope of the anonymous class. For instance, there could be references to the arguments of the enclosing method, or to temporary variables, or to fields of the hosting object. (By the language rules, the variables are all “final”.)
  • 18. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Listeners in a GUI DEMO cutButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { controller.cutEmployeeClicked(); } }); 101implementation:swing
  • 19. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Function objects Wikipedia as of 4 June 2013: “A function object [...] is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function).”
  • 20. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Sample of a functor interface /** * Functions with 1 argument */ public interface UnaryFunction<X,Y> { public Y apply(X x); }
  • 21. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Sample of a functor implementation twice( new UnaryFunction<Integer,Integer>(){ public Integer apply(Integer x) { return ++x; } }, 40 ) Exercise: suppose this expression is supposed to compute 42 because twice applies the argument twice. What’s the definition of twice?
  • 22. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Issues with Java <= 7 functors Only function objects – no functions. Verbose creation of closures. No access to non-final variables in outer scope.
  • 23. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Further reading • John Hughes: Why Functional Programming Matters, 1989, Computer Journal, available online. • Alexandre Pereira Calsavara: Achieve better Java code with inner and anonymous classes, 2003, TechRepublic, available online. • Abhijit Belapurkar: Functional programming in the Java language, 2004, IBM developerWorks, available online.
  • 24. Major use case for FOOP: Combinator libraries
  • 25. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The notion of combinator library Wikipedia as of 4 June 2013: “A combinator library is a software library which implements combinators for a functional programming language; "the key idea is this: a combinator library offers functions (the combinators) that combine functions together to make bigger functions". [...] These kinds of libraries are particularly useful for allowing domain-specific programming languages to be easily embedded into a general purpose language [...].“
  • 27. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Motivation of traversal combinators public static void cut(Company c) { Walker w = new Walker(c); for (Object o : w) if (o instanceof Employee) { Employee e = (Employee)o; e.setSalary(e.getSalary() / 2); } } http://101companies.org/wiki/Contribution:javaReflection How to be more typeful? What other traversals are conceivable?
  • 28. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Motivation of traversal combinators public static Double total(Company c) { Walker w = new Walker(c); double result = 0; for (Object o : w) if (o instanceof Employee) { Employee e = (Employee)o; result += e.getSalary(); } return result; } http://101companies.org/wiki/Contribution:javaReflection How to be more typeful? What other traversals are conceivable?
  • 29. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The paradigm of using traversal combinators Identify problem-specific ingredients: Type-specific actions or functions. Represent these ingredients as closures. Extend those ingredients into generic ones. Apply a traversal scheme. Such schemes are closure combinators. Specifically,w e useSYB style.
  • 30. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Problem-specific transformation functionality for “Cut” public static Action<Employee> updateSalary() { return new Action<Employee>() { public void apply(Employee x) { x.setSalary(x.getSalary() / 2); } }; } Update the salary when facing an employee along traversal http://101companies.org/wiki/Contribution:javaSyb
  • 31. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Problem-specific query functionality for “Total” public static Function<Employee,Double> getSalary() { return new Function<Employee, Double>() { public Double apply(Employee x) { return x.getSalary(); } }; } Extract the salary when facing an employee along traversal http://101companies.org/wiki/Contribution:javaSyb
  • 32. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Combine type-specific transformation with identity function public static <X> Action<Object> orIdentity(final Action<X> a) { return new Action<Object>() { public void apply(Object x) { try { a.apply((X)x); } catch (ClassCastException _) { } } }; } Rely on cast exception to check for applicability of type-specific case
  • 33. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Combine type-specific query with constant function public static <X,Y> Function<Object,Y> orDefault( final Function<X,Y> f, final Y otherwise) { return or(f, new Function<Object,Y>() { public Y apply(Object x) { return otherwise; } }); } or uses cast in the same way as orIdentity.
  • 34. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Apply traversal scheme for transformation public static void cut(Company c) { everywhere(orIdentity(updateSalary())).apply(c); } Try out every node
  • 35. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Apply traversal scheme for query public static Double total(Company c) { return everything( orDefault(getSalary(), 0.0), add, 0.0).apply(c); } Try out every node Add intermediate results Start from “0.0”
  • 36. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The traversal scheme everywhere public static Action<Object> everywhere( final Action<Object> a) { return new Action<Object>() { public void apply(Object x) { all(everywhere(a)).apply(x); a.apply(x); } }; } Compose an action which applies argument action a to all the subobjects reachable from the object passed to the composed action.
  • 37. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The traversal scheme everywhere public static Action<Object> everywhere( final Action<Object> a) { return new Action<Object>() { public void apply(Object x) { all(everywhere(a)).apply(x); a.apply(x); } }; } Recurse into all immediate subobjects using reflection Apply the action to the last
  • 38. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The traversal scheme everything public static <Y> Function<Object,Y> everything( final Function<Object,Y> f, final BinaryOperator<Y> op, final Y initial) { return new Function<Object,Y>() { public Y apply(Object x) { return op.apply(f.apply(x), all( everything(f, op, initial), op, initial).apply(x)); } }; } Compose a function which applies argument function f to all the subobjects reachable while composing intermediate results with the binary operator op while starting from initial.
  • 39. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The traversal scheme everything public static <Y> Function<Object,Y> everything( final Function<Object,Y> f, final BinaryOperator<Y> op, final Y initial) { return new Function<Object,Y>() { public Y apply(Object x) { return op.apply(f.apply(x), all( everything(f, op, initial), op, initial).apply(x)); } }; }
  • 40. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Traversal of companies DEMO http://101companies.org/wiki/ Contribution:javaSyb
  • 42. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) void department() { match(DEPARTMENT); match(STRING); match(OPEN); match(MANAGER); employee(); while (test(EMPLOYEE)) { match(EMPLOYEE); employee(); } while (test(DEPARTMENT)) department(); match(CLOSE); } department : 'department' STRING '{' ('manager' employee) ('employee' employee)* dept* '}'; Grammar production Corresponding procedure Motivation: how to avoid encoding of recursive descent parsing?
  • 43. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The paradigm of using parser combinators Model functor classes for acceptance & parsing. Model closure combinators for EBNF constructs. Sequence, Choice, Star, Plus, ... Model nonterminals as closure-returning methods. Encode RHS of productions in method body.
  • 44. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) The types of acceptors and parsers public abstract class Acceptor { public abstract boolean accept(Input i); } public abstract class Parser<T> { public abstract T parse(Input i); } Abstract functor classes
  • 45. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) An acceptor combinator for “*” public class Star extends Acceptor { private Acceptor a; public Star(Acceptor a) { this.a = a; } public boolean accept(Input i) { while (true) { int mark = i.getPos(); if (!a.accept(i)) { i.setPos(mark); return true; } } } } Accept input from i for as many times as possible. Make sure not to consume input that was seen when i was finally failing. (Backtracking needed.)
  • 46. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) An acceptor combinator for “*” public class Star extends Acceptor { private Acceptor a; public Star(Acceptor a) { this.a = a; } public boolean accept(Input i) { while (true) { int mark = i.getPos(); if (!a.accept(i)) { i.setPos(mark); return true; } } } } Concrete functor class
  • 47. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) public static Acceptor star(final Acceptor a) { return new Acceptor() { public boolean accept(Input i) { while (true) { int mark = i.getPos(); if (!a.accept(i)) { i.setPos(mark); return true; } } } }; } An alternative: a static function that returns a closure An acceptor combinator for “*”
  • 48. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) public class Star<T> extends Parser<List<T>> { private Parser<T> p; public Star(Parser<T> p) { this.p = p; } public List<T> parse(Input i) { List<T> r = new LinkedList<T>(); while (true) { int mark = i.getPos(); T t = p.parse(i); if (t!=null) r.add(t); else { i.setPos(mark); return r; } } } } An parser combinator for “*” Given a parser p which returns a T, construct a parser which returns a list of Ts.
  • 49. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) public class Star<T> extends Parser<List<T>> { private Parser<T> p; public Star(Parser<T> p) { this.p = p; } public List<T> parse(Input i) { List<T> r = new LinkedList<T>(); while (true) { int mark = i.getPos(); T t = p.parse(i); if (t!=null) r.add(t); else { i.setPos(mark); return r; } } } } Concrete functor class An parser combinator for “*”
  • 50. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) EBNF of 101companies company : 'company' STRING '{' department* '}' EOF; department : 'department' STRING '{' ('manager' employee) ('employee' employee)* department* '}'; employee : STRING '{' 'address' STRING 'salary' FLOAT '}'; STRING : '"' (~'"')* '"'; FLOAT : ('0'..'9')+ ('.' ('0'..'9')+)?; Let’s parse companies again.
  • 51. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Nonterminals as static fields public static final Acceptor STRING = WS(sequence( CHAR('"'), star(sequence(not(CHAR('"')),any)), CHAR('"'))); STRING : '"' (~'"')* '"';
  • 52. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Nonterminals as methods public static Acceptor department() { return new Acceptor() { public boolean accept(Input i) { return ( sequence( SPECIAL("department"), STRING, SPECIAL("{"), employee("manager"), star(employee("employee")), star(department()), SPECIAL("}") )).accept(i); } }; } department : 'department' STRING '{' ('manager' employee) ('employee' employee)* department* '}'; What’s the limit of “nonterminals as static fields”?
  • 53. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Parsing comapanies DEMO http://101companies.org/wiki/ Contribution:javaParseLib
  • 54. (C) 2010-2013 Prof. Dr. Ralf Lämmel, Universität Koblenz-Landau (where applicable) Summary Functional OOP really combines OOP and FP: OOP: Encapsulation and generalization FP: Function application, composition, combination Major use case for FOOP: combinator libraries. There are languages more suitable for functional OOP: Java 8, F#, C#, Ruby, Python, ...