hrldcpr / pcollections

A Persistent Java Collections Library
Other
765 stars 79 forks source link

PStack plusAll, unexpected result #77

Closed ghost closed 1 year ago

ghost commented 5 years ago
//[1,2]
final ConsPStack<Integer> xs = ConsPStack.<Integer>empty().plus(2).plus(1);

System.out.println(xs); // [1,2]

//[3,4]
final ConsPStack<Integer> ys = ConsPStack.<Integer>empty().plus(4).plus(3);

System.out.println(ys); // [3,4]

final ConsPStack<Integer> zs = ys.plusAll(xs);

//expected : [1,2,3,4]
System.out.println(zs); // [2,1,3,4]
hrldcpr commented 5 years ago

Hey thanks for pointing this out, it's definitely confusing…

It's because xs = xs.plusAll(ys) is equivalent to:

for (E y : ys) xs = xs.plus(y);

…so popping things off one stack and pushing them onto another ends up reversing them.

I'm not sure what the best solution is …changing the behavior at this point might break some people's code in hard-to-detect ways (though of course we would do a major version bump). Potentially could deprecate PStack.plusAll in favor of some less confusing / better-named alternative methods.