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)
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"));
}
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.
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.....)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With