= reverse =
{{{#!scheme
(define (reverse xs)
(let recur ((ys '()) (xs xs))
(if (null? xs)
ys
(recur (cons (car xs) ys) (cdr xs)))))
}}}
Notice that the ''named let'' mimics [wiki:Functions/Foldl foldl] - "constant space" tail-recursion with an accumulator.
{{{#!scheme
(define (reverse xs)
(foldl (flip cons) '() xs))
}}}
declarative
{{{#!scheme
(define reverse (partially foldl (flip cons) '()))
}}}
append-like accumulating helper, always called with {{{[]}}}
{{{#!sml
local
fun revAppend ([], ys) = ys
| revAppend (x::xs, ys) = revAppend (xs, x::ys)
in
fun rev xs = revAppend(xs,[]);
end;
}}}
{{{#!haskell
reverse l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
}}}
In terms of [wiki:Functions/Foldl foldl] and [wiki:Functions/Flip flip]
{{{#!haskell
reverse = foldl' (flip (:)) []
}}}
{{{#!haskell
reverse(X) -> reverse(X, []).
reverse([H|T], Y) -> reverse(T, [H|Y]);
reverse([], X) -> X.
}}}
{{{#!lisp
(define reverse
X -> (reverse_help X []))
(define reverse_help
[] R -> R
[X | Y] R -> (reverse_help Y [X | R]))
}}}