0

I am sure Rascal has built in support for Stack (e.g. for expression eval via stack push/pop), but I cannot find anything.

So I now use this. However is there a nicer way?

list stack = [];

pop:

value = stack[size(stack)-1];
stack = stack - value;

push

stack = stack + value
robert
  • 1,921
  • 2
  • 17
  • 27
  • Another nice way to evaluate an expression is to use recursion directly. I was wondering when you would go for an explicit stack instead; is it because you have multiple return values and don't want to use tuples or globals? or for efficiency? – Jurgen Vinju Dec 08 '14 at 09:38

2 Answers2

0

I'd recommend changing pop to:

value = stack[-1]; //short hand notation
stack = delete(stack, size(stack)-1); // to make sure the last item is deleted (in case duplicates exist in the list)
AShahi
  • 156
  • 4
  • For that second line, you can also say stack = stack[0..-1], which will do the same thing ([0..-1] is everything but the last element) and is a bit more concise. Or, just use the stack functions in List that Paul Klint mentions in his answer. – Mark Hills Dec 05 '14 at 12:19
0

Have a look at the documentation of the List module: lists support a whole zoo of stack-related functions: push, pop, top, dup, etc.

Paul Klint
  • 1,418
  • 7
  • 12
  • Yes but giving back a tuple with the value and the new list is not really convenient. Why does Rascal not support references? In that case we can do pop(myList), and after returning the value the list is also reduced. Also, this pass-by-value is it not extremely slow compared to pass-by-reference? – robert Dec 05 '14 at 12:24
  • Rascal is based on strict value semantics. This avoids many complications regarding aliasing, and increases understandability. References break this model. Under the hood, a lot of sharing is done, so the price you pay is acceptable. – Paul Klint Dec 05 '14 at 12:27
  • `pop` in List would not work for a stack since the list returned in the tuple has the first element removed instead of the last. – AShahi Dec 05 '14 at 13:03
  • Is that not precisely how stacks should behave? – Paul Klint Dec 07 '14 at 19:33