Skip to content

Instantly share code, notes, and snippets.

@jartur
Created April 21, 2014 20:54
Show Gist options
  • Save jartur/11156234 to your computer and use it in GitHub Desktop.
Save jartur/11156234 to your computer and use it in GitHub Desktop.
Optional<User> user = users.get(id);
if(user.isPresent()) {
Optional<Account> account = accounts.get(user.get());
if(account.isPresent()) {
Optional<CreditCard> card = cards.get(user.get(), account.get());
if(card.isPresent()) {
card.get().destroy();
}
}
}
or
users.get(id).bind(
user -> accounts.get(user).bind(
account -> cards.get(user, account).bind(
card -> card.destroy();
)
)
)
if we have syntax sugar
do
user <- users.get(id)
account <- accounts.get(user)
card <- cards.get(user, account)
card.destroy()
The idea is that we pass some actions that are only valid
if present action was succesfull and do not have to worry what happens if they have not been.
Mathematically it works like this:
Option a = Some a | Nothing
bind result next = if result.isPresent() {
return next(result)
} else {
return Nothing
}
For other monads it's mostly the bind operation that differs. It encodes what to do.
Collection<A> = A, Collection<A> | EmptyList
bind result next =
Collection<A> newResults = new Collection<A>()
for(r : result) {
newResults.addAll(next(result))
}
return newResults;
So if we have empty list at some point we will not even pass anything down.
E.g.
Collection<int> xs = { 1, 2, 3 }
Collection<int> ys = { 10, 100 }
xs.bind(
x -> ys.bind(
y -> y * x
))
result would be { 10, 100, 20, 200, 30, 300 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment