Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional java: what's this P1 thing?

I'm looking at Functional Java and I don't understand what a P1 is. Could anyone explain and/or give an example?

(background: I do know what currying and closures are)

like image 372
Jason S Avatar asked Apr 24 '11 19:04

Jason S


3 Answers

This is taken straight from the Google Code project for Functional Java:

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).
// Regular Java
public Integer albuquerqueToLA(Map<String, Map<String, Integer>> 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<Integer> albuquerqueToLA(TreeMap<P2<String, String>, Integer>() map) {
  return m.get(p("Albuquerque", "Los Angeles"));
}
like image 134
Cristian Sanchez Avatar answered Sep 21 '22 17:09

Cristian Sanchez


P1 looks like the 1-element, trivial product type. In Haskell it would be written as:

data P1 a = P1 a

(the Identity type in Haskell).

that is, it is a container that holds some other type a.

This type also implements the simplest monad, Identity, which allows for functions to be opaquely applied to the contents of the box.

Computationally, there is no reason to use the Identity monad instead of the much simpler act of simply applying functions to their arguments, however, it can be useful in the design of monad transformer stacks.

The monad implementation of the identity monad is trivial,

return a     = P1 a
(P1 m) >>= k = k m

As you can see, this is just function application.

like image 37
Don Stewart Avatar answered Sep 24 '22 17:09

Don Stewart


aha, found this post:

>>> Also, P1 is potentially lazy. We use it for the implementation of
>>> Stream, for example. 

So instead of returning type T directly, I can have something that returns P1<T>, much like Google Collections Supplier<T>, and have it compute the contained value only when P1._1() is called.

(huh, this blog post Lazy Error Handling in Java was interesting too.....)

like image 38
Jason S Avatar answered Sep 25 '22 17:09

Jason S