10
$\begingroup$

A stack-based language necessarily contains at least "push" and "pop" instructions. However, these typically aren't the only ways to manipulate the stack. For example, several languages have an instruction to swap the two values at the top of the stack. Trilangle has an instruction to look arbitrarily far down the stack, but I don't know how common that is.

What are some of the most common stack manipulation operations, and what benefits do they provide?

$\endgroup$
1

2 Answers 2

11
$\begingroup$

Data for this post comes from the Vyxal element corpus and the 05AB1E element corpus, both of which show the most commonly used built-ins from over 1500 answers in each language on the code golf stack exchange. It also comes from a list of things languages like Forth and Factor have

Here's a list of some things that are helpful for a stack language. Their stack effects are given as stack before -> stack after:

  • Pop (a -> ) and push ( -> a) (as mentioned in the question)
  • Duplicate (dup) a -> a a
  • Over a b -> a b a
  • Swap a b -> b a (also mentioned in the question)
  • Wrap into list a b c ... -> [a, b, c, ...]
  • Rotate left a b c ... -> b c ... a
  • Rotate right a b c ... -> ... a b c
  • Rotate a b c -> c a b
  • triplicate (duplicate then duplicate again) a -> a a a
  • n-licate (duplicate n times) a -> a a ... a
  • nip (alternatively, swap-pop) a b -> b and a b c -> a c
  • 2dup a b -> a b a b
  • n-over (over but the nth item from the top) a b c ... -> a b c ... stack[len(stack) - n] (thanks to @mousetail for the suggestion) (mentioned in question too)
  • push stack length a b c ... -> a b c ... len(stack)
  • dump x, [a, b, c] -> x a b c
$\endgroup$
5
  • $\begingroup$ Does nip truncate the whole thing (i.e. a ... b c -> c) or is it equivalent to swap-pop? $\endgroup$
    – Bbrk24
    Commented May 17, 2023 at 11:36
  • $\begingroup$ the factor documentation for nip suggests swap-pop $\endgroup$
    – lyxal
    Commented May 17, 2023 at 11:40
  • $\begingroup$ N-over is also really useful, copy the N-th element to the front $\endgroup$
    – mousetail
    Commented May 17, 2023 at 12:10
  • 1
    $\begingroup$ N-over appears to be the same thing as the “indexed read” operator I mentioned in the question, with the difference being that Trilangle’s operator pulls the value of n off the top of the stack. $\endgroup$
    – Bbrk24
    Commented May 17, 2023 at 14:14
  • 4
    $\begingroup$ "Whole stack" operations like "wrap into list" are common in esoteric and recreational golfing languages, but some of the more "serious" stack-based languages like Factor and Cat tend to avoid those since they're pretty difficult to do static analysis against. $\endgroup$ Commented May 17, 2023 at 14:32
4
$\begingroup$

Stack manipulation instructions in various bytecode formats:

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .