wiki:Functions/Reverse

reverse

(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 foldl - "constant space" tail-recursion with an accumulator.

(define (reverse xs)
   (foldl (flip cons) '() xs))

declarative

(define reverse (partially foldl (flip cons) '()))

append-like accumulating helper, always called with []

local
  fun revAppend ([], ys) = ys
    | revAppend (x::xs, ys) = revAppend (xs, x::ys)
in
    fun rev xs = revAppend(xs,[]);
end;
reverse l =  rev l []
  where
    rev []     a = a
    rev (x:xs) a = rev xs (x:a)

In terms of foldl and flip

reverse  =  foldl' (flip (:)) []
reverse(X) -> reverse(X, []).

reverse([H|T], Y) -> reverse(T, [H|Y]);
reverse([], X) -> X.
(define reverse
  X -> (reverse_help X []))

(define reverse_help
  [] R -> R
  [X | Y] R -> (reverse_help Y [X | R]))
Last modified 2 years ago Last modified on Oct 24, 2018, 10:17:43 AM
Note: See TracWiki for help on using the wiki.