Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Lua

Idiom #19 Reverse a list

Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.

function array_reverse(x)
  local n, m = #x, #x/2
  for i=1, m do
    x[i], x[n-i+1] = x[n-i+1], x[i]
  end
  return x
end
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end

-- in-situ reversal
function reverse(t)
  local n = #t
  local i = 1
  for i = 1, n do
    t[i],t[n] = t[n],t[i]

    n = n - 1
  end
end
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end
x = rev
with Ada.Containers.Vectors;
use Ada.Containers;
X.Reverse_Elements;

New implementation...
< >
programming-idioms.org