Variants/case classes/algebraic data types/sums/oh my!

Victor Nazarov asviraspossible at gmail.com
Sun Jun 12 22:59:02 UTC 2016


12 июня 2016 г. 18:26 пользователь "Brian Goetz" <brian.goetz at oracle.com>
написал:

>
>>
>> It does sound quite wonderful. This actually came up in conversation
>> with someone recently, but do you think that lambdas will benefit from
>> this work? It seems that with the combination of escape analysis and
>> value types, you could stack allocate closures.
>
>
> Yes, this is an obvious goal.  We were careful to define the semantics of
lambda capture to disavow any assumptions of identity, which would allow us
to (eventually) represent lambdas as values, including lambdas with
captures.  The cost difference between stateless and capturing lambdas is
entirely an accident of representation, and with a better representation,
this can be improved.
>
> That said, the hard part of getting here is not the VM mechanics, but how
it fits into the type system, and maintaining compatibility with how things
work now.
>
>

Hi. I'm the author of adt4j[1] library. Following this discussion I'm
starting to realise that maybe specialization is the only missing peace for
ADT support in Java.
If lambdas become values than specialization question becomes really
interesting.

Is foreach method like below to be automatically specialized for every
consumer-lambda argument

class MyCollection<E> {
public <any C extends Consumer<E>> void forEach(C Consumer) {...}}

If specialization is to really work like this than this is enough to
provide support for ADTs without any overhead. ADTs can be defined using
generic-visitor pattern like this.

interface ExprVisitor<any R> {
    R lit(int v);
    R add(Expr left, Expr right);
}
class Expr {
public <any V extends ExprVisitor<R>, any R> R accept(V visitor);}

If accept method is to be specialized for every value-type used as visitor
than the only missing feature is language level way to define anonymous
value-types like this

int eval(Expr expr) {
    return expr.accept(new value ExprVisitor<int>() {
        int lit(int n) { return n; }
        int add(Expr left, Expr right) { return eval(left) + eval(right); }
});
}

If everything works than such method is known to perform no allocations
wich are the main problem with visitor pattern today.
--
Victor Nazarov

[1] https://github.com/sviperll/adt4j



More information about the valhalla-dev mailing list