Skip to content

Updated features with Google site examples #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions src/jbake/content/features.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,158 @@
:jbake-tags:
:jbake-status: published

== First-Class Functions

Functional Java provides generic interfaces and abstract classes that serve as first-class functions or closures, entirely within Java's type system (i.e. without reflection or byte-code manipulation). The library centers around the F interface, which models a function from type A to type B.

Functions are written with anonymous class syntax:

[source,java]
----
// Regular Style
Integer timesTwo(Integer i) { return i * 2; }
// Functional Style
F timesTwo = new F() { public Integer f(Integer i) { return i * 2; } }
----

First-class functions can be composed and passed as arguments to higher-order functions:

[source,java]
----
// Regular Style
Integer timesTwoPlusOne(Integer i) { return plusOne(timesTwo(i)); }
// Functional Style
F timesTwoPlusOne = plusOne.o(timesTwo);
----

And mapped over collections:

[source,java]
----
//Regular Style
List oneUp = new ArrayList();
for (Integer i: ints) oneUp.add(plusOne(i));
// Functional Style
List oneUp = ints.map(plusOne);
----

Functions up to arity-8 are supported, allowing elimination of nested control constructs:

[source,java]
----
// Regular Style
Integer product = 1;
for (Integer x: ints) product = x * product;
List products1 = new ArrayList();
for (int x = 0; x < ints.size(); x++) {
for (int y = 0; y <= x; y++) {
products.add(ints.get(x) * ints.get(y);
}
}
List products2 = new ArrayList();
for (Integer x: ints) {
for (Integer y: ints) {
products.add(x * y);
}
}
// Functional Style
Integer product = ints.foldLeft(1, multiply);
List products1 = ints.tails().apply(ints.map(multiply));
List products2 = ints.bind(ints, multiply);
----

== Immutable Datastructures

Functional Java implements many immutable datastructures, such as

* Singly-linked lists (`fj.data.List`)
* Non-strict, potentially infinite, singly-linked list (`fj.data.Stream`)
* Non-strict, potentially infinite Strings (`fj.data.LazyString`)
* A wrapper for arrays (`fj.data.Array`)
* A wrapper for any Iterable type (`fj.data.IterableW`)
* Immutable ordered sets (`fj.data.Set`)
* Multi-way trees -- a.k.a. rose trees, with support for infinite trees (`fj.data.Tree`)
* Immutable Map, with single-traversal search-and-update (`fj.data.TreeMap`)
* Type-safe heterogeneous lists (`fj.data.hlist`)
* Pointed lists and trees (`fj.data.Zipper` and `fj.data.TreeZipper`)

These datatypes come with many powerful higher-order functions, such as map (for functors), bind (monads), apply and zipWith (applicative functors), and cobind (for comonads).

Efficient conversions to and from the standard Java Collections classes are provided, and `java.util.Iterable` is implemented where possible, for use with Java's foreach syntax.

== Optional Values (type-safe null)

The library provides a datatype for variables, parameters, and return values that may have no value, while remaining type-safe.

[source,java]
----
// Using null
String val = map.get(key);
if (val == null || val.equals("")) val = "Nothing";
return val;
// Using Option
return fromString(map.get(key)).orSome("Nothing");
----

Optional values are iterable, so they play nicely with foreach syntax, and they can be composed in a variety of ways. The fj.Option class has a plethora of methods for manipulating optional values, including many higher-order functions.

== Product Types

Joint union types (tuples) are products of other types. Products of arities 1-8 are provided (`fj.P1` - `fj.P8`). These are useful for when you want to return more than one value from a function, or when you want to accept several values when implementing an interface method that accepts only one argument. They can also be used to get products over other datatypes, such as lists (zip function).

Example:

[source,java]
----
// Regular Java
public Integer albuquerqueToLA(Map> map) {
Map m = map.get("Albuquerque");
if (m != null) return m.get("Los Angeles"); // May return null.
}
// Functional Java with product and option types.
public Option albuquerqueToLA(TreeMap, Integer>() map) {
return m.get(p("Albuquerque", "Los Angeles"));
}
----

== Disjoint Union Types

By the same token, types can be added by disjoint union. Values of type `Either<A, B>` contain a value of either type `A` or type `B`. This has many uses. As an argument type, it allows a single argument to depend on the type of value that is received (effectively overloading the method even if the interface is not designed to do that). As a return type, it allows you to return a value of one of two types depending on some condition. For example, to provide error handling where you are not allowed to throw `Exception`s:

[source,java]
----
// Meanwhile, inside an iterator implementation...
public Either next() {
String s = moreInput();
try {
return Either.right(Integer.valueOf(s));
} catch (Exception e) {
return Either.left(Fail.invalidInteger(s));
}
}
----

The `Either` class includes a lot of useful methods, including higher-order functions for mapping and binding over the left and right types, as well as Iterable implementations for both types.

http://apocalisp.wordpress.com/2008/06/04/throwing-away-throws[See here for a more detailed explanation of using `Either` for handling errors.]

== Higher-Order Concurrency Abstractions

Functional Java includes Parallel Strategies (fj.control.parallel.Strategy) for effectively decoupling concurrency patterns from algorithms. Strategy provides higher-order functions for mapping and binding over collections in parallel:

[source,java]
----
Strategy s = simpleThreadStrategy();
List ns = range(Integer.MIN_VALUE, Integer.MIN_VALUE + 10).map(negate).toList();
List bs = s.parMap(ns, isPrime);
----

Also included is an implementation of the actor model (`fj.control.parallel.Actor` and `QueueActor`), and `Promise`, which is a composable and non-blocking version of `java.util.concurrent.Future`.

http://apocalisp.wordpress.com/2008/06/30/parallel-list-transformations[A series of blog posts on the concurrency features can be found here.]

== Abstractions

Functional Java provides abstractions for the following types:

* Basic Data Structures
Expand Down