functional programming in Java - java

how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?
map(func, new String[]{"a","b","c"});
what's the least verbose & awkward way to do it?

All attempts of functional programming will have some part of verbose and/or awkward to it in Java, until Java 8.
The most direct way is to provide a Function interface (such as this one form Guava) and provide all kinds of methods that take and call it (such as Collections#transfrom() which does what I think your map() method should do).
The bad thing about is that you need to implement Function and often do so with an anonymous inner class, which has a terribly verbose syntax:
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
Lambda expressions (introduced in Java 8) make this considerably easier (and possibly faster). The equivalent code using lambdas looks like this:
Collection<OutputType> result = Collections.transform(input, SomeClass::frobnicate);
or the more verbose, but more flexible:
Collection<OutputType> result = Collections.transform(input, in -> frobnicate(in));

I have used lambdaj and functionaljava for this sort of things. And there are probably others...

Just wrap the function you want to apply on the list with a class or an interface.
public interface Func {
Object f(Object input);
}
public void map (Func func, Object[] arr) {
for(int i=0;i<arr.legnth;i++) {
arr[i] = func.f(arr[i]);
}
}
map(
new Func() { public Object f(Object input) { return input; } };,
new String[]{"a","b"});

As you note, Java isn't designed for functional programming and while you can emulate it, you have to really want to do this even if is it more verbose and more awkward than using standard programming in Java.
Take #Joachim's example.
Collection<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
public OutputType apply(InputType input) {
return frobnicate(input);
}
});
This uses 12 symbols, not counting close brackets. The same thing in plain Java would look like.
List<OutputType> list = new ArrayList();
for(InputType in: input)
list.add(frobnicate(in));
This uses 7 symbols.
You can do functional programming in Java, but you should expect it to be more verbose and awkward than using the natural programming style of Java.

You could download OpenJDK 8 which is scheduled for prodcution release next year and use the new Lambda Expressions for functional programming. See http://macgyverdev.blogspot.se/2012/10/functional-programming-in-java.html for examples of how these closures will be used in the Collection APIs and how they compare with pre-Java 8 solutions like Guava and LambdaJ.

Related

What is a closure's real value proposition besides information hiding in multi-paradigm / functional languages like JavaScript?

When I first tried to understand closures, I was met by an impenetrable wall of paper of incomprehensibly presented computer science I had to understand before I could touch a closure. Then I learned, on more of a monkey see, monkey do basis, that while JavaScript keywords did not allow Java's idiom, of (excuse my hazy memory here):
JAVA:
class ObjectWithPrivateMember()
{
private int counter;
public void ObjectWithPrivateMember()
{
counter = 0;
}
public void increment()
{
counter += 1;
}
public void decrement()
{
counter -= 1;
}
public void get_count()
{
return counter;
}
}
JavaScript (ECMAScript as of some years back) had no real "private" / "protected" keyword, but a free translation of the Java idiom might be something like:
JAVASCRIPT:
var object_with_private_member = function()
{
var counter = 0;
return {
increment: function()
{
counter += 1;
},
decrement: function()
{
counter -= 1;
},
get_count: function()
{
return counter;
}
};
}();
And besides my immediate reaction of "Ewwwww, duct tape to try to dress up JavaScript as something it's not," I had mentally filed that as, "Ok, that is how to shoehorn the Java idiom with obscure details of JavaScript. This probably affords little direct insight into what is great about JavaScript."
Now that I came back to address the question "What are closures really good for?", the Wikipedia entry gives a few details and suggests that information hiding may be a primary use case, not just in multi-paradigm languages with a heavy functional bent, but the usual suspects for first-class functional languages. Of course it is more detailed and offers more nuance, but it suggests that the textbook "JavaScript object with private fields" use case is not nearly as tangential as I assumed it was.
What is (are) the real use case(s) a good functional programmer would see for closures in pure functional languages or multi-paradigm languages with a functional bent? Are they primarily used for information hiding (the Wikipedia article offers more nuance and detail than the caricature above, but at least at first blush my thought was that closures probably had a bigger and more interesting role in JavaScript than a backdoor way to create private members.
Are there other major use cases besides a mechanism for information hiding in pure / multi-paradigm functional languages?
The privacy thing is a minor consideration, in my experience, especially with immutable values. Why do you care who sees it, if they can't change it?
To understand the value of closures, you first must understand the value of first-class functions, then it's fairly easy to see when it might be handy to associate some data with that function.
Consider trying to write the following example from the wikipedia page without using closures, but still using the filter higher-order function:
// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
return bookList.filter(
function (book) { return book.sales >= threshold; }
);
}
You need to find some other way of communicating the threshold to the predicate function. In OOP, you would create some sort of object like:
class ThresholdFilter implements Filterable {
private threshold;
ThresholdFilter(threshold) {
this.threshold = threshold;
}
bool filter(book) {
return book.sales >= this.threshold;
}
}
function bestSellingBooks(threshold) {
return bookList.filter(new ThresholdFilter(threshold));
}
Alternately, you could change the filter function to accept some sort of private generic data structure to store and pass on, which makes both filter and the predicate function more complicated and more coupled. Closures are starting to look pretty good right about now, am I right?
There are many more cases where closures vastly reduce coupling and simplify code that uses higher-order functions. It's a major reason why functional programs are so much more concise.

Is there a way to compare lambdas?

Say I have a List of object which were defined using lambda expressions (closures). Is there a way to inspect them so they can be compared?
The code I am most interested in is
List<Strategy> strategies = getStrategies();
Strategy a = (Strategy) this::a;
if (strategies.contains(a)) { // ...
The full code is
import java.util.Arrays;
import java.util.List;
public class ClosureEqualsMain {
interface Strategy {
void invoke(/*args*/);
default boolean equals(Object o) { // doesn't compile
return Closures.equals(this, o);
}
}
public void a() { }
public void b() { }
public void c() { }
public List<Strategy> getStrategies() {
return Arrays.asList(this::a, this::b, this::c);
}
private void testStrategies() {
List<Strategy> strategies = getStrategies();
System.out.println(strategies);
Strategy a = (Strategy) this::a;
// prints false
System.out.println("strategies.contains(this::a) is " + strategies.contains(a));
}
public static void main(String... ignored) {
new ClosureEqualsMain().testStrategies();
}
enum Closures {;
public static <Closure> boolean equals(Closure c1, Closure c2) {
// This doesn't compare the contents
// like others immutables e.g. String
return c1.equals(c2);
}
public static <Closure> int hashCode(Closure c) {
return // a hashCode which can detect duplicates for a Set<Strategy>
}
public static <Closure> String asString(Closure c) {
return // something better than Object.toString();
}
}
public String toString() {
return "my-ClosureEqualsMain";
}
}
It would appear the only solution is to define each lambda as a field and only use those fields. If you want to print out the method called, you are better off using Method. Is there a better way with lambda expressions?
Also, is it possible to print a lambda and get something human readable? If you print this::a instead of
ClosureEqualsMain$$Lambda$1/821270929#3f99bd52
get something like
ClosureEqualsMain.a()
or even use this.toString and the method.
my-ClosureEqualsMain.a();
This question could be interpreted relative to the specification or the implementation. Obviously, implementations could change, but you might be willing to rewrite your code when that happens, so I'll answer at both.
It also depends on what you want to do. Are you looking to optimize, or are you looking for ironclad guarantees that two instances are (or are not) the same function? (If the latter, you're going to find yourself at odds with computational physics, in that even problems as simple as asking whether two functions compute the same thing are undecidable.)
From a specification perspective, the language spec promises only that the result of evaluating (not invoking) a lambda expression is an instance of a class implementing the target functional interface. It makes no promises about the identity, or degree of aliasing, of the result. This is by design, to give implementations maximal flexibility to offer better performance (this is how lambdas can be faster than inner classes; we're not tied to the "must create unique instance" constraint that inner classes are.)
So basically, the spec doesn't give you much, except obviously that two lambdas that are reference-equal (==) are going to compute the same function.
From an implementation perspective, you can conclude a little more. There is (currently, may change) a 1:1 relationship between the synthetic classes that implement lambdas, and the capture sites in the program. So two separate bits of code that capture "x -> x + 1" may well be mapped to different classes. But if you evaluate the same lambda at the same capture site, and that lambda is non-capturing, you get the same instance, which can be compared with reference equality.
If your lambdas are serializable, they'll give up their state more easily, in exchange for sacrificing some performance and security (no free lunch.)
One area where it might be practical to tweak the definition of equality is with method references because this would enable them to be used as listeners and be properly unregistered. This is under consideration.
I think what you're trying to get to is: if two lambdas are converted to the same functional interface, are represented by the same behavior function, and have identical captured args, they're the same
Unfortunately, this is both hard to do (for non-serializable lambdas, you can't get at all the components of that) and not enough (because two separately compiled files could convert the same lambda to the same functional interface type, and you wouldn't be able to tell.)
The EG discussed whether to expose enough information to be able to make these judgments, as well as discussing whether lambdas should implement more selective equals/hashCode or more descriptive toString. The conclusion was that we were not willing to pay anything in performance cost to make this information available to the caller (bad tradeoff, punishing 99.99% of users for something that benefits .01%).
A definitive conclusion on toString was not reached but left open to be revisited in the future. However, there were some good arguments made on both sides on this issue; this is not a slam-dunk.
To compare labmdas I usually let the interface extend Serializable and then compare the serialized bytes. Not very nice but works for the most cases.
I don't see a possibility, to get those informations from the closure itself.
The closures doesn't provide state.
But you can use Java-Reflection, if you want to inspect and compare the methods.
Of course that is not a very beautiful solution, because of the performance and the exceptions, which are to catch. But this way you get those meta-informations.

Monads with Java 8

In the interests of helping to understand what a monad is, can someone provide an example using java ? Are they possible ?
Lambda expressions are possible using java if you download the pre-release lambda compatible JDK8 from here http://jdk8.java.net/lambda/
An example of a lambda using this JDK is shown below, can someone provide a comparably simple monad ?
public interface TransformService {
int[] transform(List<Integer> inputs);
}
public static void main(String ars[]) {
TransformService transformService = (inputs) -> {
int[] ints = new int[inputs.size()];
int i = 0;
for (Integer element : inputs) {
ints[i] = element;
}
return ints;
};
List<Integer> inputs = new ArrayList<Integer>(5) {{
add(10);
add(10);
}};
int[] results = transformService.transform(inputs);
}
Just FYI:
The proposed JDK8 Optional class does satisfy the three Monad laws. Here's a gist demonstrating that.
All it takes be a Monad is to provide two functions which conform to three laws.
The two functions:
Place a value into monadic context
Haskell's Maybe: return / Just
Scala's Option: Some
Functional Java's Option: Option.some
JDK8's Optional: Optional.of
Apply a function in monadic context
Haskell's Maybe: >>= (aka bind)
Scala's Option: flatMap
Functional Java's Option: flatMap
JDK8's Optional: flatMap
Please see the above gist for a java demonstration of the three laws.
NOTE: One of the key things to understand is the signature of the function to apply in monadic context: it takes the raw value type, and returns the monadic type.
In other words, if you have an instance of Optional<Integer>, the functions you can pass to its flatMap method will have the signature (Integer) -> Optional<U>, where U is a value type which does not have to be Integer, for example String:
Optional<Integer> maybeInteger = Optional.of(1);
// Function that takes Integer and returns Optional<Integer>
Optional<Integer> maybePlusOne = maybeInteger.flatMap(n -> Optional.of(n + 1));
// Function that takes Integer and returns Optional<String>
Optional<String> maybeString = maybePlusOne.flatMap(n -> Optional.of(n.toString));
You don't need any sort of Monad Interface to code this way, or to think this way. In Scala, you don't code to a Monad Interface (unless you are using Scalaz library...). It appears that JDK8 will empower Java folks to use this style of chained monadic computations as well.
Hope this is helpful!
Update: Blogged about this here.
Java 8 will have lambdas; monads are a whole different story. They are hard enough to explain in functional programming (as evidenced by the large number of tutorials on the subject in Haskell and Scala).
Monads are a typical feature of statically typed functional languages. To describe them in OO-speak, you could imagine a Monad interface. Classes that implement Monad would then be called 'monadic', provided that in implementing Monad the implementation obeys what are known as the 'monad laws'. The language then provides some syntactic sugar that makes working with instances of the Monad class interesting.
Now Iterable in Java has nothing to do with monads, but as a example of a type that the Java compiler treats specially (the foreach syntax that came with Java 5), consider this:
Iterable<Something> things = getThings(..);
for (Something s: things) { /* do something with s */ }
So while we could have used Iterable's Iterator methods (hasNext and company) in an old-style for loop, Java grants us this syntactic sugar as a special case.
So just as classes that implement Iterable and Iterator must obey the Iterator laws (Example: hasNext must return false if there is no next element) to be useful in foreach syntax - there would exist several monadic classes that would be useful with a corresponding do notation (as it is called in Haskell) or Scala's for notation.
So -
What are good examples of monadic classes?
What would syntactic sugar for dealing with them look like?
In Java 8, I don't know - I am aware of the lambda notation but I am not aware of other special syntactic sugar, so I'll have to give you an example in another language.
Monads often serve as container classes (Lists are an example). Java already has java.util.List which is obviously not monadic, but here is Scala's:
val nums = List(1, 2, 3, 4)
val strs = List("hello", "hola")
val result = for { // Iterate both lists, return a resulting list that contains
// pairs of (Int, String) s.t the string size is same as the num.
n <- nums
s <- strs if n == s.length
} yield (n, s)
// result will be List((4, "hola"))
// A list of exactly one element, the pair (4, "hola")
Which is (roughly) syntactic sugar for:
val nums = List(1, 2, 3, 4)
val strs = List("hello", "hola")
val results =
nums.flatMap( n =>
strs.filter(s => s.size == n). // same as the 'if'
map(s => (n, s)) // Same as the 'yield'
)
// flatMap takes a lambda as an argument, as do filter and map
//
This shows a feature of Scala where monads are exploited to provide list comprehensions.
So a List in Scala is a monad, because it obeys Scala's monad laws, which stipulate that all monad implementations must have conforming flatMap, map and filter methods (if you are interested in the laws, the "Monads are Elephants" blog entry has the best description I've found so far). And, as you can see, lambdas (and HoF) are absolutely necessary but not sufficient to make this kind of thing useful in a practical way.
There's a bunch of useful monads besides the container-ish ones as well. They have all kinds of applications. My favorite must be the Option monad in Scala (the Maybe monad in Haskell), which is a wrapper type which brings about null safety: the Scala API page for the Option monad has a very simple example usage: http://www.scala-lang.org/api/current/scala/Option.html
In Haskell, monads are useful in representing IO, as a way of working around the fact that non-monadic Haskell code has indeterminate order of execution.
Having lambdas is a first small step into the functional programming world; monads
require both the monad convention and a large enough set of usable monadic types, as well as syntactic sugar to make working with them fun and useful.
Since Scala is arguably the language closest to Java that also allows (monadic) Functional Programming, do look at this Monad tutorial for Scala if you are (still) interested:
http://james-iry.blogspot.jp/2007/09/monads-are-elephants-part-1.html
A cursory googling shows that there is at least one attempt to do this in Java: https://github.com/RichardWarburton/Monads-in-Java -
Sadly, explaining monads in Java (even with lambdas) is as hard as explaining full-blown Object oriented programming in ANSI C (instead of C++ or Java).
Even though monads can be implemented in Java, any computation involving them is doomed to become a messy mix of generics and curly braces.
I'd say that Java is definitely not the language to use in order to illustrate their working or to study their meaning and essence. For this purpose it is far better to use JavaScript or to pay some extra price and learn Haskell.
Anyway, I am signaling you that I just implemented a state monad using the new Java 8 lambdas. It's definitely a pet project, but it works on a non-trivial test case.
You may find it presented at my blog, but I'll give you some details here.
A state monad is basically a function from a state to a pair (state,content). You usually give the state a generic type S and the content a generic type A.
Because Java does not have pairs we have to model them using a specific class, let's call it Scp (state-content pair), which in this case will have generic type Scp<S,A> and a constructor new Scp<S,A>(S state,A content). After doing that we can say that the monadic function will have type
java.util.function.Function<S,Scp<S,A>>
which is a #FunctionalInterface. That's to say that its one and only implementation method can be invoked without naming it, passing a lambda expression with the right type.
The class StateMonad<S,A> is mainly a wrapper around the function. Its constructor may be invoked e.g. with
new StateMonad<Integer, String>(n -> new Scp<Integer, String>(n + 1, "value"));
The state monad stores the function as an instance variable. It is then necessary to provide a public method to access it and feed it the state. I decided to call it s2scp ("state to state-content pair").
To complete the definition of the monad you have to provide a unit (aka return) and a bind (aka flatMap) method. Personally I prefer to specify unit as static, whereas bind is an instance member.
In the case of the state monad, unit gotta be the following:
public static <S, A> StateMonad<S, A> unit(A a) {
return new StateMonad<S, A>((S s) -> new Scp<S, A>(s, a));
}
while bind (as instance member) is:
public <B> StateMonad<S, B> bind(final Function<A, StateMonad<S, B>> famb) {
return new StateMonad<S, B>((S s) -> {
Scp<S, A> currentPair = this.s2scp(s);
return famb(currentPair.content).s2scp(currentPair.state);
});
}
You notice that bind must introduce a generic type B, because it is the mechanism that allows the chaining of heterogeneous state monads and gives this and any other monad the remarkable capability to move the computation from type to type.
I'd stop here with the Java code. The complex stuff is in the GitHub project. Compared to previous Java versions, lambdas remove a lot of curly braces, but the syntax is still pretty convoluted.
Just as an aside, I'm showing how similar state monad code may be written in other mainstream languages. In the case of Scala, bind (which in that case must be called flatMap) reads like
def flatMap[A, B](famb: A => State[S, B]) = new State[S, B]((s: S) => {
val (ss: S, aa: A) = this.s2scp(s)
famb(aa).s2scp(ss)
})
whereas the bind in JavaScript is my favorite; 100% functional, lean and mean but -of course- typeless:
var bind = function(famb){
return state(function(s) {
var a = this(s);
return famb(a.value)(a.state);
});
};
<shameless>
I am cutting a few corners here, but if you are interested in the details you will find them on my WP blog.</shameless>
Here's the thing about monads which is hard to grasp: monads are a
pattern, not a specific type. Monads are a shape, they are an abstract
interface (not in the Java sense) more than they are a concrete data
structure. As a result, any example-driven tutorial is doomed to
incompleteness and failure.
[...]
The only way to understand monads is to see them for what they are: a mathematical construct.
Monads are not metaphors by Daniel Spiewak
Monads in Java SE 8
List monad
interface Person {
List<Person> parents();
default List<Person> greatGrandParents1() {
List<Person> list = new ArrayList<>();
for (Person p : parents()) {
for (Person gp : p.parents()) {
for (Person ggp : p.parents()) {
list.add(ggp);
}
}
}
return list;
}
// <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
default List<Person> greatGrandParents2() {
return Stream.of(parents())
.flatMap(p -> Stream.of(p.parents()))
.flatMap(gp -> Stream.of(gp.parents()))
.collect(toList());
}
}
Maybe monad
interface Person {
String firstName();
String middleName();
String lastName();
default String fullName1() {
String fName = firstName();
if (fName != null) {
String mName = middleName();
if (mName != null) {
String lName = lastName();
if (lName != null) {
return fName + " " + mName + " " + lName;
}
}
}
return null;
}
// <U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
default Optional<String> fullName2() {
return Optional.ofNullable(firstName())
.flatMap(fName -> Optional.ofNullable(middleName())
.flatMap(mName -> Optional.ofNullable(lastName())
.flatMap(lName -> Optional.of(fName + " " + mName + " " + lName))));
}
}
Monad is a generic pattern for nested control flow encapsulation.
I.e. a way to create reusable components from nested imperative idioms.
Important to understand that a monad is not just a generic wrapper class with a flat map operation.
For example, ArrayList with a flatMap method won't be a monad.
Because monad laws prohibit side effects.
Monad is a formalism. It describes the structure, regardless of content or meaning.
People struggle with relating to meaningless (abstract) things.
So they come up with metaphors which are not monads.
See also:
conversation between Erik Meijer and Gilad Bracha.
the only way to understand monads is by writing a bunch of combinator libraries, noticing the resulting duplication, and then discovering for yourself that monads let you factor out this duplication. In discovering this, everyone builds some intuition for what a monad is… but this intuition isn’t the sort of thing that you can communicate to someone else directly – it seems everyone has to go through the same experience of generalizing to monads from some concrete examples of combinator libraries. however
here i found some materials to learn Mondas.
hope to be useful for you too.
codecommit
james-iry.blogspot
debasishg.blogspot
This blog post gives a step-by-step example of how you might implement a Monad type (interface) in Java and then use it to define the Maybe monad, as a practical application.
This post explains that there is one monad built into the Java language, emphasising the point that monads are more common than many programmers may think and that coders often inadvertently reinvent them.
Despite all controversy about Optional satisfying, or not, the Monad laws, I usually like to look at Stream, Optional and CompletableFuture in the same way. In truth, all them provide a flatMap() and that is all I care and let me embrace the "the tasteful composition of side effects" (cited by Erik Meijer). So we may have corresponding Stream, Optional and CompletableFuture in the following way:
Regarding Monads, I usually simplify it only thinking on flatMap()(from "Principles of Reactive Programming" course by Erik Meijer):
A diagram for the "Optional" Monad in Java.
Your task: Perform operations on the "Actuals" (left side) transforming elements of type T union null to type U union null using the function in the light blue box (the light blue box function). Just one box is shown here, but there may be a chain of the light blue boxes (thus proceeding from type U union null to type V _union null to type W union null etc.)
Practically, this will cause you to worry about null values appearing in the function application chain. Ugly!
Solution: Wrap your T into an Optional<T> using the light green box functions, moving to the "Optionals" (right side). Here, transform elements of type Optional<T> to type Optional<U> using the red box function. Mirroring the application of functions to the "Actuals", there may be several red box functions to be be chained (thus proceeding from type Optional<U> to Optional<V> then to Optional<W> etc.). In the end, move back from the "Optionals" to the "Actuals" through one of the dark green box functions.
No worrying about null values anymore. Implementationwise, there will always be an Optional<U>, which may or may not be empty. You can chain the calls to to the red box functions without null checks.
The key point: The red box functions are not implemented individually and directly. Instead, they are obtained from the blue box functions (whichever have been implemented and are available, generally the light blue ones) by using either the map or the flatMap higher-order functions.
The grey boxes provide additional support functionality.
Simples.
I like to think of monads in slighlty more mathematical (but still informal) fashion. After that I will explain the relationship to one of Java 8's monads CompletableFuture.
First of all, a monad M is a functor. That is, it transforms a type into another type: If X is a type (e.g. String) then we have another type M<X> (e.g. List<String>). Moreover, if we have a transformation/function X -> Y of types, we should get a function M<X> -> M<Y>.
But there is more data to such a monad. We have a so-called unit which is a function X -> M<X> for each type X. In other words, each object of X can be wrapped in a natural way into the monad.
The most characteristic data of a monad, however, is it's product: a function M<M<X>> -> M<X> for each type X.
All of these data should satisfy some axioms like functoriality, associativity, unit laws, but I won't go into detail here and it also doesn't matter for practical usage.
We can now deduce another operation for monads, which is often used as an equivalent definition for monads, the binding operation: A value/object in M<X> can be bound with a function X -> M<Y> to yield another value in M<Y>. How do we achieve this? Well, first we apply functoriality to the function to obtain a function M<X> -> M<M<Y>>. Next we apply the monadic product to the target to obtain a function M<X> -> M<Y>. Now we can plug in the value of M<X> to obtain a value in M<Y> as desired. This binding operation is used to chain several monadic operations together.
Now lets come to the CompletableFuture example, i.e. CompletableFuture = M. Think of an object of CompletableFuture<MyData> as some computation that's performed asynchronously and which yields an object of MyData as a result some time in the future. What are the monadic operations here?
functoriality is realized with the method thenApply: first the computation is performed and as soon as the result is available, the function which is given to thenApply is applied to transform the result into another type
the monadic unit is realized with the method completedFuture: as the documentation tells, the resulting computation is already finished and yields the given value at once
the monadic product is not realized by a function, but the binding operation below is equivalent to it (together with functoriality) and its semantic meaning is simply the following: given a computation of type CompletableFuture<CompletableFuture<MyData>> that computation asynchronously yields another computation in CompletableFuture<MyData> which in turn yields some value in MyData later on, so performing both computations on after the other yields one computation in total
the resulting binding operation is realized by the method thenCompose
As you see, computations can now be wrapped up in a special context, namely asynchronicity. The general monadic structures enable us to chain such computations in the given context. CompletableFuture is for example used in the Lagom framework to easily construct highly asynchronous request handlers which are transparently backed up by efficient thread pools (instead of handling each request by a dedicated thread).
Haskell monads is an interface which specify rules to convert “datatype that is wrapped in another datatype” to another “datatype that is wrapped in another or same datatype”; the conversion steps is specified by a function you define with a format.
The function format takes a datatype and return “datatype that is wrapped in another datatype”. You can specify operations/ calculations during conversion e.g. multiply or lookup something.
It is so difficult to understand because of the nested abstraction. It is so abstracted so that you can reuse the rules to convert datatype in a datatype without custom programming to unwrap the first “ datatype that is wrapped in another datatype” before putting the data to your specified function; Optional with some datatype is an example of “datatype in a datatype”.
The specified function is any lambda confirming the format.
You don’t need to fully understand it; you will write your own reusable interface to solve similar problem. Monad is just exist because some mathematicians already hit and resolve that problem, and create monad for you to reuse. But due to its abstraction, it is difficult to learn and reuse in the first place.
In other words, e.g. Optional is a wrapper class, but some data is wrapped , some not, some function take wrapped data type but some don’t, return type can be of type wrapped or not. To chain calling mixture of function which may wrap or not in parameter/return types, you either do your own custom wrap/unwrap or reuse pattern of functor / applicative / monad to deal with all those wrapped/unwrapped combinations of chained function call. Every time u try to put optional to a method that only accept plain value and return optional, the steps are what monad does.

Try/do pattern implementation in Java

I'm a fan of the try/do (or trier/doer) pattern, which is best implemented in C# using out parameters, e.g.:
DateTime date;
if (DateTime.TryParse("2012-06-18", out date))
{
//Do something with date
}
I'm currently working on a Java 1.5 project, for which I'm implementing the try/do pattern using a new class called TryResult which is returned from any methods which implement the try/do pattern:
public class TryResult<ResultType> {
private boolean mSuccess = false;
private ResultType mResult = null;
public TryResult(boolean success, ResultType result) {
super();
this.mSuccess = success;
this.mResult = result;
}
public boolean isSuccess() {
return mSuccess;
}
public ResultType getResult() {
return mResult;
}
}
This is working well, but I will be porting this code to a different platform which uses J2ME, and therefore generics aren't available.
My current options are to either remove the generics from the TryResult class above and using plain old Object and casting, or make a new class for the types I will end up using (e.g. StringTryResult).
Is there a better way to implement this pattern on J2ME/Java 1.3?
What you are trying to implement is called a Maybe monad in functional languages.
There are experiments to do this in java, see here and here.
The problem is, Java's type system is unfortunately not advanced enough to support this on a large scale.. Also, the standard libraries do not support anything like that, which reduces the use of such a construct to your own code only :(
See Scala and Clojure for languages that support this.
As far as Java ME goes, I'd think twice about implementing special types just for the sake of this. It is a nice in idea theory, however, it would make things just more difficult, eg. duplicating all types in your whole app.
I don't endorse this an any way, but a really low-tech way to do "out" variables in Java is to use single element arrays:
String input = ...;
Date[] date = { null };
if (DateParser.tryParse(input, date)) {
System.out.println(date[0]);
}

What are good patterns / techniques to reduce verbosity of Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
One of the things that can be a little annoying about Java is the amount of code you need to express concepts. I am a believer in the "less code is better" philosophy, and I'd like to know how I can write Java without being so frustratingly verbose. Recently, I read the Hidden Features of Java question and was introduced to using double-brace initialization to simulate a List or Map literal. There are, of course, drawbacks to using this method, but it does allow you to do certain things with significantly fewer characters and (if you format it right) make the code a lot cleaner and clearer. I'm wondering if there aren't other clever tricks and lesser known language features which could make my code more concise.
I'd like to see answers with an explanation of the technique, the more verbose way which it replaces, and any potential drawbacks to using the technique.
Prior to the introduction of the diamond operator in Java 7, static factory methods for creating generic types could be used to reduce verbosity by reducing the need to repeat the type parameter. (This is because without the diamond operator, Java never infers the type parameter on constructors, but it will on methods calls.) Google Collections uses this technique, so you can write:
Set<MyClassWithALongName> set = Sets.newHashSet();
instead of:
Set<MyClassWithALongName> set = new HashSet<MyClassWithALongName>();
Look in the Lists, Sets and Maps classes of Google Collections for methods starting with "new" for more examples of this.
Unless you are writing for an old version of Java, as of Java 7 it is better to just use the diamond operator.
A similar one you probably already know about, using the "varargs" feature:
String[] array = new String[] {"stack", "over", "flow"};
List<String> list = Arrays.asList(array);
can be abbreviated
List<String> list = Arrays.asList("stack", "over", "flow");
Admittedly not a huge savings, but it does reduce the verbosity a little bit. As Thomas notes, the list will be immutable, so watch out for that. Actually, you can modify the list, you just can't change its length. Thanks to pimlottc for pointing that out.
Use a dependency injection framework like spring. I'm almost always amazed at how much code construction logic produces.
I've found that the most (only?) effective way to write concise java is to not write java at all. In cases where I needed to write something quickly that still interoperates with Java, I've found Groovy to be an excellent choice. Using a more concise language that still compiles to JVM bytecode can be an excellent solution. While I have no personal experiences with it, I've heard that Scala is an even better choice than Groovy in many cases.
Check out lambdaj. It has lots of features that can help to make your code more concise and readable.
Fluent interfaces can help - using builders and method chaining to make something resembling a DSL in java. The code you end up with can be a little harder to read though as it breaks Java's normal coding conventions such as removing the set / get from properties.
So in a fake Swing fluent interface you might define a button thus:
JButton button = Factory.button().icon(anIcon).tooltip("Wow").swing();
Another approach is to use another language there are many that integrate well with the JVM such as:
JRuby
Scala
Cal
A "closeQuietly" method can be used in try/finally blocks in situations where IO exceptions on close are uninteresting (or impossible).
Closeable c = null;
try {
...
c = openIt(...);
...
} finally {
closeQuietly(c);
}
where:
/** Close 'c' if it is not null, squashing IOExceptions */
public void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ex) {
// log error
}
}
}
Note that with Java 7 and later, the new "try with resources" syntax makes this particular example redundant.
I found a blog post giving an interesting technique which allows for writing a map literal in Java like you would be able to do in Perl, Python, Ruby, etc: Building your own literals in Java - Tuples and Maps
I really like this approach! I'll just summarize it here.
The basic idea is to create a generic pair class and define static functions that will construct a pair, and a map from a varargs array of pairs. This allows the following concise map literal definition:
Map(o("height", 3), o("width", 15), o("weight", 27));
Where o is the name of the static function to construct a pair of T1 and T2 objects, for any object types T1 and T2, and Map is the name of the static function to construct a Map. I'm not sure I like the choice of Map as the name of the map construction function because it is the same as the name of the Java interface, but the concept is still good.
Static initialisers
Example 1 (Map):
Map<String, String> myMap = new HashMap<String, String>() {{
put ("a", "b");
put ("c", "d");
}};
Example 2(List):
List<String> myList = new ArrayList<String>() {{
add("a");
add("b");
add("c");
}};
More Guave goodness to initialize immutable maps (which I'm finding to be a way more common case than initializing mutable maps): the ImmutableMap.of(...) variants
Map<Service, Long> timeouts = ImmutableMap.of(
orderService, 1500,
itemService, 500);
Ever have to iterate through a collection, just to map its elements by one of its properties? No more, thanks to Maps.uniqueIndex():
private void process(List<Module> modules) {
Map<String, Module> byName = Maps.uniqueIndex(modules, new Function<Module, String>() {
#Override public String apply(Module input) {
return input.getName();
}
});
or if this is frequent enough, make the function a public static final member of Module so that the above is reduced to:
Map<String, Module> byName = Maps.uniqueIndex(modules, Module.KEY_FUNCTION);

Categories