When I first
read Java implementation of Lamda, the first thing came in my mind was this is
nothing but our old C function pointers (I suppose coming from C background I
made a wrong assumption).
For
e.g.
BiPredicate<Integer,
Integer> bi = (x, y) -> x > y;
//
I thought equivalent C code would be as follows:
boolean
isGreater(int x, int y) { return x > y; }
boolean
(*bi)(int, int) = &isGreater;
void
main() {
boolean
result = bi(10,20)
}
//
Note: boolean is symbolic in terms of C J
This was all
good until I came across ‘negate’ function within BiPredicate, for e.g:
BiPredicate<Integer,
Integer> bi = (x, y) -> x > y;
BiPredicate<Integer,
Integer> negateBi = bi.negate();
System.out.println(negateBi.test(2,
3));
The ‘BiPredicate::negate’
implementation confused me, which is:
default BiPredicate<T, U>
negate() {
return (T t, U u) -> !test(t,
u);
}
The only way
I could think of simulating ‘negate’ FP (Function Pointer) in C is, by defining
an another function such as ‘isNotGreater’ and by using previous FP ‘bi’ in its
implementation as follows:
boolean
isNotGreater(int x, int y) { return !bi(x,y); }
int
(*negate)(int, int) = &isNotGreater;
From the
above C code; it is clear that, ‘negate’
FP needs reference to the ‘bi’ FP instance
to be able to work. Hence Lamda implementation is not all about function
pointers but also related to the data binding.
Conclusion:
Calling ‘BiPredicate::negate’
function -> is creating a new predicate (‘negate’ in our example) , which
internally is storing a reference to the previous predicate ‘bi’ (This
behaviour can be described as data-binding).
No comments:
Post a Comment