SlideShare uma empresa Scribd logo
1 de 52
Baixar para ler offline
by Mario Fusco
mario.fusco@gmail.com
twitter: @mariofusco

Monadic
Imperative languages

Java

C#
C / C++

Fortran

Subtract abstractions

Scala
Add abstractions

F#
Hybrid languages

Algol
Lisp
ML
Haskell
Functional languages
new language < new paradigm
Learning a new language is relatively easy
compared with learning a new paradigm.

Functional Programming is more a new way of
thinking than a new tool set
What is a monad?
A monad is a triple (T, η, μ) where T is an endofunctor T: X  X
and η: I  T and μ: T x T  T are 2 natural transformations
satisfying these laws:
Identity law:
μ(η(T)) = T = μ(T(η))
Associative law: μ(μ(T × T) × T)) = μ(T × μ(T × T))
In other words: "a monad in X is just a monoid in the category of
endofunctors of X, with product × replaced by composition of
endofunctors and unit set by the identity endofunctor"

What's the problem?
… really? do I need to know this?
In order to understand
monads you need to first
learn Cathegory Theory
… it's like saying …

In order to understand
pizza you need to first
learn Italian
… ok, so let's try to ask Google …
… no seriously, what is a monad?
A
monad
is a
structure
that puts a
value
in a
computational context
… and why should we care about?
Reduce code duplication
Improve maintainability
Increase readability
Remove side effects
Hide complexity
Encapusalate implementation details
Allow composability
Monadic Methods
M<A> unit(A a);
M<B> bind(M<A> ma, Function<A, M<B>> f);
Monadic Methods
M<A> unit(A a);
M<B> bind(M<A> ma, Function<A, M<B>> f);

interface M {
M<B> map(Function<A, B> f);

M<B> flatMap(Function<A, M<B>> f);
}
Monadic Methods
M<A> unit(A a);
M<B> bind(M<A> ma, Function<A, M<B>> f);

interface M {
M<B> map(Function<A, B> f);
{
return flatMap( x -> unit( f.apply(x) ) );
}
M<B> flatMap(Function<A, M<B>> f);
}

map can defined for every monad as
a combination of flatMap and unit
Finding Car's Insurance Name
public class Person {
private Car car;
public Car getCar() { return car; }
}
public class Car {
private Insurance insurance;
public Insurance getInsurance() { return insurance; }
}
public class Insurance {
private String name;
public String getName() { return name; }
}
Attempt 1: deep doubts
String getCarInsuranceName(Person person) {
if (person != null) {
Car car = person.getCar();
if (car != null) {
Insurance insurance = car.getInsurance;
if (insurance != null) {
return insurance.getName()
}
}
}
return "Unknown";
}
Attempt 2: too many choices
String getCarInsuranceName(Person person) {
if (person == null) {
return "Unknown";
}
Car car = person.getCar();
if (car == null) {
return "Unknown";
}
Insurance insurance = car.getInsurance();
if (insurance == null) {
return "Unknown";
}
return insurance.getName()
}
Optional Monad to the rescue
public class Optional<T> {
private static final Optional<?> EMPTY = new Optional<>(null);
private final T value;

private Optional(T value) {
this.value = value;
}
public<U> Optional<U> map(Function<? super T, ? extends U> f) {
return value == null ? EMPTY : new Optional(f.apply(value));
}
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> f) {
return value == null ? EMPTY : f.apply(value);
}
}
Rethinking our model
public class Person {
private Optional<Car> car;
public Optional<Car> getCar() { return car; }
}

Using the type system
to model nullable value

public class Car {
private Optional<Insurance> insurance;
public Optional<Insurance> getInsurance() { return insurance; }
}

public class Insurance {
private String name;
public String getName() { return name; }
}
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional

Person
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
flatMap(person -> person.getCar())

Person
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
Optional
flatMap(person -> person.getCar())

Car
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
flatMap(car -> car.getInsurance())

Car
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
Optional
flatMap(car -> car.getInsurance())

Insurance
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
map(insurance -> insurance.getName())

Insurance
Restoring the sanity
String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(person -> person.getCar())
.flatMap(car -> car.getInsurance())
.map(insurance -> insurance.getName())
.orElse("Unknown");
}

Optional
orElse("Unknown")

String
Why map and flatMap ?
flatMap defines monad's policy
for monads composition
person
.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");

map defines monad's policy
for function application
The Optional Monad
The Optional monad makes
the possibility of missing data
explicit
in the type system, while
hiding
the boilerplate of "if non-null" logic
Stream: another Java8 monad
Given n>0 find all pairs i and j
where 1 ≤ j ≤ i ≤ n and i+j is prime
Stream.iterate(1, i -> i+1).limit(n)
.flatMap(i -> Stream.iterate(1, j -> j+1).limit(n)
.map(j -> new int[]{i, j}))
.filter(pair -> isPrime(pair[0] + pair[1]))
.collect(toList());

public boolean isPrime(int n) {
return Stream.iterate(2, i -> i+1)
.limit((long) Math.sqrt(n))
.noneMatch(i -> n % i == 0);
}
The Stream Monad
The Stream monad makes
the possibility of multiple data
explicit
in the type system, while
hiding
the boilerplate of nested loops
No Monads syntactic sugar in Java :(
for { i <- List.range(1, n)
j <- List.range(1, i)
if isPrime(i + j) } yield {i, j}

translated by the compiler in

List.range(1, n)
.flatMap(i =>
List.range(1, i)
.filter(j => isPrime(i+j))
.map(j => (i, j)))

Scala's for-comprehension
is just syntactic sugar to
manipulate monads
Are there other monads
in Java8 API?
CompletableFuture
CompletableFuture
Promise: a monadic CompletableFuture
public class Promise<A> implements Future<A> {
private final CompletableFuture<A> future;
private Promise(CompletableFuture<A> future) {
this.future = future;
}
public static final <A> Promise<A> promise(Supplier<A> supplier) {
return new
Promise<A>(CompletableFuture.supplyAsync(supplier));
}

public <B>
return
}
public <B>
return

Promise<B> map(Function<? super A,? extends B> f) {
new Promise<B>(future.thenApplyAsync(f));
Promise<B> flatMap(Function<? super A, Promise<B>> f) {
new Promise<B>(
future.thenComposeAsync(a -> f.apply(a).future));

}
// ... omitting methods delegating the wrapped future
}
Composing long computations
public int slowLength(String s) {
someLongComputation();
return s.length();
}

public int slowDouble(int i) {
someLongComputation();
return i*2;
}

String s = "Hello";
Promise<Integer> p = promise(() -> slowLength(s))
.flatMap(i -> promise(() -> slowDouble(i)));
The Promise Monad
The Promise monad makes
asynchronous computation
explicit
in the type system, while
hiding
the boilerplate thread logic
Creating our own Monad
Lost in Exceptions
public Person validateAge(Person p) throws ValidationException {
if (p.getAge() > 0 && p.getAge() < 130) return p;
throw new ValidationException("Age must be between 0 and 130");
}
public Person validateName(Person p) throws ValidationException {
if (Character.isUpperCase(p.getName().charAt(0))) return p;
throw new ValidationException("Name must start with uppercase");
}
List<String> errors = new ArrayList<String>();
try {
validateAge(person);
} catch (ValidationException ex) {
errors.add(ex.getMessage());
}
try {
validateName(person);
} catch (ValidationException ex) {
errors.add(ex.getMessage());
}
Defining a Validation Monad
public abstract class Validation<L, A> {

protected final A value;
private Validation(A value) {
this.value = value;
}
public abstract <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper);

public abstract <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper);
public abstract boolean isSuccess();
}
Success !!!
public class Success<L, A> extends Validation<L, A> {
private Success(A value) { super(value); }
public <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper) {
return success(mapper.apply(value));
}

public <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
return (Validation<L, B>) mapper.apply(value);
}
public boolean isSuccess() { return true; }
public static <L, A> Success<L, A> success(A value) {
return new Success<L, A>(value);
}
}
Failure :(((
public class Failure<L, A> extends Validation<L, A> {
protected final L left;
public Failure(A value, L left) {super(value); this.left = left;}
public <B> Validation<L, B> map(
Function<? super A, ? extends B> mapper) {
return failure(left, mapper.apply(value));
}
public <B> Validation<L, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return result.isSuccess() ?
failure(left, result.value) :
failure(((Failure<L, B>)result).left, result.value);
}
public boolean isSuccess() { return false; }
}
The Validation Monad
The Validation monad makes
the possibility of errors
explicit
in the type system, while
hiding
the boilerplate of "try/catch" logic
Rewriting validating methods
public Validation<String, Person> validateAge(Person p) {
return (p.getAge() > 0 && p.getAge() < 130) ?
success(p) :
failure("Age must be between 0 and 130", p);
}

public Validation<String, Person> validateName(Person p) {
return Character.isUpperCase(p.getName().charAt(0)) ?
success(p) :
failure("Name must start with uppercase", p);
}
Lesson learned:
Leverage the Type System
Gathering multiple errors - Success
public class SuccessList<L, A> extends Success<List<L>, A> {
public SuccessList(A value) { super(value); }

public <B> Validation<List<L>, B> map(
Function<? super A, ? extends B> mapper) {
return new SuccessList(mapper.apply(value));
}
public <B> Validation<List<L>, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return (Validation<List<L>, B>)(result.isSuccess() ?
new SuccessList(result.value) :
new FailureList<L, B>(((Failure<L, B>)result).left,
result.value));
}

}
Gathering multiple errors - Failure
public class FailureList<L, A> extends Failure<List<L>, A> {
private FailureList(List<L> left, A value) { super(left, value); }

public <B> Validation<List<L>, B> map(
Function<? super A, ? extends B> mapper) {
return new FailureList(left, mapper.apply(value));
}
public <B> Validation<List<L>, B> flatMap(
Function<? super A, Validation<?, ? extends B>> mapper) {
Validation<?, ? extends B> result = mapper.apply(value);
return (Validation<List<L>, B>)(result.isSuccess() ?
new FailureList(left, result.value) :
new FailureList<L, B>(new ArrayList<L>(left) {{
add(((Failure<L, B>)result).left);
}}, result.value));
}
}
Monadic Validation
Validation<List<String>, Person>
validatedPerson = success(person).failList()
.flatMap(Validator::validAge)
.flatMap(Validator::validName);
Homework: develop your own
Transaction Monad

The Transaction monad makes
transactionality
explicit
in the type system, while
hiding
the boilerplate propagation of invoking rollbacks
To recap: a Monad is a design pattern
Alias
 flatMap that shit
Intent
 Put a value in a computational context defining the policy
on how to operate on it
Motivations
 Reduce code duplication
 Improve maintainability
 Increase readability
 Remove side effects
 Hide complexity
 Encapusalate implementation details
 Allow composability
Known Uses
 Optional, Stream, Promise, Validation, Transaction, State, …
TL;DR

Use Monads whenever possible
to keep your code clean and
encapsulate repetetive logic
Thanks … Questions?

Q
Mario Fusco
Red Hat – Senior Software Engineer

A
mario.fusco@gmail.com
twitter: @mariofusco

Mais conteúdo relacionado

Mais procurados

Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaSierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaPhilip Schwarz
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardKelsey Gilmore-Innis
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does notSergey Bandysik
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Philip Schwarz
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 

Mais procurados (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and ScalaSierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
Sierpinski Triangle - Polyglot FP for Fun and Profit - Haskell and Scala
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
3 kotlin vs. java- what kotlin has that java does not
3  kotlin vs. java- what kotlin has that java does not3  kotlin vs. java- what kotlin has that java does not
3 kotlin vs. java- what kotlin has that java does not
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 

Destaque

Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal ProgrammersStephan February
 
Functional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptFunctional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptPavel Klimiankou
 
[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two MonadsFunctional Thursday
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production DebuggingTakipi
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaC4Media
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Monica Beckwith
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
 

Destaque (12)

Monads in practice
Monads in practiceMonads in practice
Monads in practice
 
Monads
MonadsMonads
Monads
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal Programmers
 
Functional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptFunctional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScript
 
[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To Java
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!
 
In Search of Segmentation
In Search of SegmentationIn Search of Segmentation
In Search of Segmentation
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 

Semelhante a Monadic Java

MonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfMonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfEonisGonzara1
 
For the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfFor the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfarjunhassan8
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyoneBartek Witczak
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
Creating an Uber Clone - Part XXVI.pdf
Creating an Uber Clone - Part XXVI.pdfCreating an Uber Clone - Part XXVI.pdf
Creating an Uber Clone - Part XXVI.pdfShaiAlmog1
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo....NET Conf UY
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعةجامعة القدس المفتوحة
 

Semelhante a Monadic Java (20)

MonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdfMonadicJava_-_reviwed.pdf
MonadicJava_-_reviwed.pdf
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Exam2prep
Exam2prepExam2prep
Exam2prep
 
For the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdfFor the following questions, you will implement the data structure to.pdf
For the following questions, you will implement the data structure to.pdf
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
 
DotNet Conference: code smells
DotNet Conference: code smellsDotNet Conference: code smells
DotNet Conference: code smells
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
Creating an Uber Clone - Part XXVI.pdf
Creating an Uber Clone - Part XXVI.pdfCreating an Uber Clone - Part XXVI.pdf
Creating an Uber Clone - Part XXVI.pdf
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
 

Mais de Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

Mais de Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Último (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

Monadic Java

  • 2. Imperative languages Java C# C / C++ Fortran Subtract abstractions Scala Add abstractions F# Hybrid languages Algol Lisp ML Haskell Functional languages
  • 3. new language < new paradigm Learning a new language is relatively easy compared with learning a new paradigm. Functional Programming is more a new way of thinking than a new tool set
  • 4. What is a monad? A monad is a triple (T, η, μ) where T is an endofunctor T: X  X and η: I  T and μ: T x T  T are 2 natural transformations satisfying these laws: Identity law: μ(η(T)) = T = μ(T(η)) Associative law: μ(μ(T × T) × T)) = μ(T × μ(T × T)) In other words: "a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor" What's the problem?
  • 5. … really? do I need to know this? In order to understand monads you need to first learn Cathegory Theory … it's like saying … In order to understand pizza you need to first learn Italian
  • 6. … ok, so let's try to ask Google …
  • 7. … no seriously, what is a monad? A monad is a structure that puts a value in a computational context
  • 8. … and why should we care about? Reduce code duplication Improve maintainability Increase readability Remove side effects Hide complexity Encapusalate implementation details Allow composability
  • 9. Monadic Methods M<A> unit(A a); M<B> bind(M<A> ma, Function<A, M<B>> f);
  • 10. Monadic Methods M<A> unit(A a); M<B> bind(M<A> ma, Function<A, M<B>> f); interface M { M<B> map(Function<A, B> f); M<B> flatMap(Function<A, M<B>> f); }
  • 11. Monadic Methods M<A> unit(A a); M<B> bind(M<A> ma, Function<A, M<B>> f); interface M { M<B> map(Function<A, B> f); { return flatMap( x -> unit( f.apply(x) ) ); } M<B> flatMap(Function<A, M<B>> f); } map can defined for every monad as a combination of flatMap and unit
  • 12. Finding Car's Insurance Name public class Person { private Car car; public Car getCar() { return car; } } public class Car { private Insurance insurance; public Insurance getInsurance() { return insurance; } } public class Insurance { private String name; public String getName() { return name; } }
  • 13. Attempt 1: deep doubts String getCarInsuranceName(Person person) { if (person != null) { Car car = person.getCar(); if (car != null) { Insurance insurance = car.getInsurance; if (insurance != null) { return insurance.getName() } } } return "Unknown"; }
  • 14. Attempt 2: too many choices String getCarInsuranceName(Person person) { if (person == null) { return "Unknown"; } Car car = person.getCar(); if (car == null) { return "Unknown"; } Insurance insurance = car.getInsurance(); if (insurance == null) { return "Unknown"; } return insurance.getName() }
  • 15. Optional Monad to the rescue public class Optional<T> { private static final Optional<?> EMPTY = new Optional<>(null); private final T value; private Optional(T value) { this.value = value; } public<U> Optional<U> map(Function<? super T, ? extends U> f) { return value == null ? EMPTY : new Optional(f.apply(value)); } public<U> Optional<U> flatMap(Function<? super T, Optional<U>> f) { return value == null ? EMPTY : f.apply(value); } }
  • 16. Rethinking our model public class Person { private Optional<Car> car; public Optional<Car> getCar() { return car; } } Using the type system to model nullable value public class Car { private Optional<Insurance> insurance; public Optional<Insurance> getInsurance() { return insurance; } } public class Insurance { private String name; public String getName() { return name; } }
  • 17. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); }
  • 18. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional Person
  • 19. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional flatMap(person -> person.getCar()) Person
  • 20. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional Optional flatMap(person -> person.getCar()) Car
  • 21. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional flatMap(car -> car.getInsurance()) Car
  • 22. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional Optional flatMap(car -> car.getInsurance()) Insurance
  • 23. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional map(insurance -> insurance.getName()) Insurance
  • 24. Restoring the sanity String getCarInsuranceName(Optional<Person> person) { return person.flatMap(person -> person.getCar()) .flatMap(car -> car.getInsurance()) .map(insurance -> insurance.getName()) .orElse("Unknown"); } Optional orElse("Unknown") String
  • 25. Why map and flatMap ? flatMap defines monad's policy for monads composition person .flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknown"); map defines monad's policy for function application
  • 26. The Optional Monad The Optional monad makes the possibility of missing data explicit in the type system, while hiding the boilerplate of "if non-null" logic
  • 28. Given n>0 find all pairs i and j where 1 ≤ j ≤ i ≤ n and i+j is prime Stream.iterate(1, i -> i+1).limit(n) .flatMap(i -> Stream.iterate(1, j -> j+1).limit(n) .map(j -> new int[]{i, j})) .filter(pair -> isPrime(pair[0] + pair[1])) .collect(toList()); public boolean isPrime(int n) { return Stream.iterate(2, i -> i+1) .limit((long) Math.sqrt(n)) .noneMatch(i -> n % i == 0); }
  • 29. The Stream Monad The Stream monad makes the possibility of multiple data explicit in the type system, while hiding the boilerplate of nested loops
  • 30. No Monads syntactic sugar in Java :( for { i <- List.range(1, n) j <- List.range(1, i) if isPrime(i + j) } yield {i, j} translated by the compiler in List.range(1, n) .flatMap(i => List.range(1, i) .filter(j => isPrime(i+j)) .map(j => (i, j))) Scala's for-comprehension is just syntactic sugar to manipulate monads
  • 31. Are there other monads in Java8 API?
  • 34. Promise: a monadic CompletableFuture public class Promise<A> implements Future<A> { private final CompletableFuture<A> future; private Promise(CompletableFuture<A> future) { this.future = future; } public static final <A> Promise<A> promise(Supplier<A> supplier) { return new Promise<A>(CompletableFuture.supplyAsync(supplier)); } public <B> return } public <B> return Promise<B> map(Function<? super A,? extends B> f) { new Promise<B>(future.thenApplyAsync(f)); Promise<B> flatMap(Function<? super A, Promise<B>> f) { new Promise<B>( future.thenComposeAsync(a -> f.apply(a).future)); } // ... omitting methods delegating the wrapped future }
  • 35. Composing long computations public int slowLength(String s) { someLongComputation(); return s.length(); } public int slowDouble(int i) { someLongComputation(); return i*2; } String s = "Hello"; Promise<Integer> p = promise(() -> slowLength(s)) .flatMap(i -> promise(() -> slowDouble(i)));
  • 36. The Promise Monad The Promise monad makes asynchronous computation explicit in the type system, while hiding the boilerplate thread logic
  • 38. Lost in Exceptions public Person validateAge(Person p) throws ValidationException { if (p.getAge() > 0 && p.getAge() < 130) return p; throw new ValidationException("Age must be between 0 and 130"); } public Person validateName(Person p) throws ValidationException { if (Character.isUpperCase(p.getName().charAt(0))) return p; throw new ValidationException("Name must start with uppercase"); } List<String> errors = new ArrayList<String>(); try { validateAge(person); } catch (ValidationException ex) { errors.add(ex.getMessage()); } try { validateName(person); } catch (ValidationException ex) { errors.add(ex.getMessage()); }
  • 39. Defining a Validation Monad public abstract class Validation<L, A> { protected final A value; private Validation(A value) { this.value = value; } public abstract <B> Validation<L, B> map( Function<? super A, ? extends B> mapper); public abstract <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper); public abstract boolean isSuccess(); }
  • 40. Success !!! public class Success<L, A> extends Validation<L, A> { private Success(A value) { super(value); } public <B> Validation<L, B> map( Function<? super A, ? extends B> mapper) { return success(mapper.apply(value)); } public <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { return (Validation<L, B>) mapper.apply(value); } public boolean isSuccess() { return true; } public static <L, A> Success<L, A> success(A value) { return new Success<L, A>(value); } }
  • 41. Failure :((( public class Failure<L, A> extends Validation<L, A> { protected final L left; public Failure(A value, L left) {super(value); this.left = left;} public <B> Validation<L, B> map( Function<? super A, ? extends B> mapper) { return failure(left, mapper.apply(value)); } public <B> Validation<L, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return result.isSuccess() ? failure(left, result.value) : failure(((Failure<L, B>)result).left, result.value); } public boolean isSuccess() { return false; } }
  • 42. The Validation Monad The Validation monad makes the possibility of errors explicit in the type system, while hiding the boilerplate of "try/catch" logic
  • 43. Rewriting validating methods public Validation<String, Person> validateAge(Person p) { return (p.getAge() > 0 && p.getAge() < 130) ? success(p) : failure("Age must be between 0 and 130", p); } public Validation<String, Person> validateName(Person p) { return Character.isUpperCase(p.getName().charAt(0)) ? success(p) : failure("Name must start with uppercase", p); }
  • 45. Gathering multiple errors - Success public class SuccessList<L, A> extends Success<List<L>, A> { public SuccessList(A value) { super(value); } public <B> Validation<List<L>, B> map( Function<? super A, ? extends B> mapper) { return new SuccessList(mapper.apply(value)); } public <B> Validation<List<L>, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return (Validation<List<L>, B>)(result.isSuccess() ? new SuccessList(result.value) : new FailureList<L, B>(((Failure<L, B>)result).left, result.value)); } }
  • 46. Gathering multiple errors - Failure public class FailureList<L, A> extends Failure<List<L>, A> { private FailureList(List<L> left, A value) { super(left, value); } public <B> Validation<List<L>, B> map( Function<? super A, ? extends B> mapper) { return new FailureList(left, mapper.apply(value)); } public <B> Validation<List<L>, B> flatMap( Function<? super A, Validation<?, ? extends B>> mapper) { Validation<?, ? extends B> result = mapper.apply(value); return (Validation<List<L>, B>)(result.isSuccess() ? new FailureList(left, result.value) : new FailureList<L, B>(new ArrayList<L>(left) {{ add(((Failure<L, B>)result).left); }}, result.value)); } }
  • 47. Monadic Validation Validation<List<String>, Person> validatedPerson = success(person).failList() .flatMap(Validator::validAge) .flatMap(Validator::validName);
  • 48. Homework: develop your own Transaction Monad The Transaction monad makes transactionality explicit in the type system, while hiding the boilerplate propagation of invoking rollbacks
  • 49. To recap: a Monad is a design pattern Alias  flatMap that shit Intent  Put a value in a computational context defining the policy on how to operate on it Motivations  Reduce code duplication  Improve maintainability  Increase readability  Remove side effects  Hide complexity  Encapusalate implementation details  Allow composability Known Uses  Optional, Stream, Promise, Validation, Transaction, State, …
  • 50. TL;DR Use Monads whenever possible to keep your code clean and encapsulate repetetive logic
  • 51.
  • 52. Thanks … Questions? Q Mario Fusco Red Hat – Senior Software Engineer A mario.fusco@gmail.com twitter: @mariofusco