Left-right fold equivalence 2026-10-31
For finite lists, if and , then the right fold with step and seed equals the left fold with step and seed . The two steps need not be identical. Equality of the resulting values does not imply equal time complexity; list concatenation is an important example.
Left scan 2026-10-31
Return the successive accumulator values of a left fold, including the initial accumulator:
scanl f e [] = [e] and scanl f e (x:xs) = e : scanl f (f e x) xs. The th result is the fold of the first elements, proved by the fold equation. Thus the scan equals map (foldl f e) . inits, but computes updates instead of on a finite input of length . Accumulator strictness and the cost of an update remain separate from this operation count.In a least-significant-first bit-serial comparator, the new pair has higher significance than every pair already processed. Equal new bits preserve the earlier result; unequal new bits decide the new result regardless of earlier bits. Use a left fold starting at equality:
type Bit = Int
data LEG = Lt | Eq | Gt deriving (Eq, Show)
step :: LEG -> (Bit,Bit) -> LEG
step old (a,b)
| a < b = Lt
| a > b = Gt
| otherwise = old
compare :: [Bit] -> [Bit] -> LEG
compare as bs = foldl step Eq (pairs as bs)
where
pairs [] [] = []
pairs (a:as) [] = (a,0) : pairs as []
pairs [] (b:bs) = (0,b) : pairs [] bs
pairs (a:as) (b:bs) = (a,b) : pairs as bsInputs have the precondition that each
Bit is 0 or 1. Equal-length inputs are the physical circuit case; pairs also gives a defined unsigned meaning to unequal lengths by padding the shorter input with high-order zeros. Ordinary zip would silently discard significant unmatched bits.After pairs the fold accumulator compares and . Equal new bits add the same amount. If , the new difference has magnitude , exceeding the maximum magnitude of the earlier difference. This proves the accumulator invariant and givesFor the four pairs in the source, the states are
Lt, Gt, Gt, Lt, so the final result compares correctly.The map function transforms each head and recursively processes the tail. A right fold combines a head with the result for its tail, whereas a left fold passes an updated accumulator into the recursive call. In Haskell:
import Prelude hiding (map, foldr, foldl, concat)
map f [] = []
map f (x:xs) = f x : map f xs
foldr op e [] = e
foldr op e (x:xs) = op x (foldr op e xs)
foldl op e [] = e
foldl op e (x:xs) = foldl op (op e x) xs
concat = foldr (++) []The last right fold uses list concatenation to replace each outer cons by appending its inner list. Thus
concat [xs,ys,zs] = xs ++ (ys ++ (zs ++ [])). Its right fold association matters: appending a list traverses its left spine, so these equations traverse each inner spine once on finite inputs. The concise answer isUse function extensionality: show for every value of the argument type. In lazy evaluation semantics, “every value” includes the bottom value and partial values. For list arguments, structural induction on lazy lists supplies the empty, bottom and cons cases, with continuity justifying passage to infinite lists.
The original printed equation has the same right fold on both sides, including the same operator and seed; this is visible in the scan.[ref]
Functional programming, data structures and algorithms, procedural programming, and digital hardware examination paper by the University of Oxford (2005). Printed p. 2, Question 1(c), displayed equation
Thus its literal answer isFor every input , both sides denote the very same expression foldr (oplus) e xs; equality follows by reflexivity. This remains true if its value is . Neither termination nor associativity nor an identity law is required. The scan does not establish a different intended equation, so no replacement by a left fold is assumed.Use structural induction on the finite list
xs, strengthening the induction hypothesis to hold for every accumulator value . For the empty list, the defining equation of the left fold givesFor the inductive step, suppose the identity holds for the tail zs and every accumulator. Expand the first left fold, apply the induction hypothesis at accumulator , and then use the supplied compatibility law:HenceOnly equation (1) is needed for this part; the seed condition in equation (2) enters the next proof. Quantifying over the accumulator is essential because the recursive call changes it.Again use structural induction on the finite list. At
[], both the right fold and the left fold return the seed . If they agree on zs, thenThe third line uses part (a); the fourth uses equation (2). Thus the left-right fold equivalence isThis is a statement about values on finite, total inputs. It does not assert equal evaluation costs or equal behaviour on infinite lists.Write , with . At the th step of the left fold, the left operand of list concatenation is the accumulated prefix of length . Fully forcing these concatenations repeatedly copies earlier elements. Including the traversal of the outer list and the whole output spine givesFor singleton inner lists, this becomes , whereas the right fold takes . More generally, for equal positive length , the left fold takes .
An bound is tight in the worst case over length distributions, but is not a tight formula for every distribution: if all elements occur only in the final inner list, all earlier accumulators are empty and the cost is . Lazy evaluation changes when the work happens; it does not remove repeated prefix traversal when the whole result is demanded.
These operations consume the receiver, as expected for this destructive iterator interface. For
exists stops immediately after the first successful test.trait RichIter[T] extends Iter[T] {
def foreach(f: T => Unit): Unit = {
while (hasNext) f(next())
}
def exists(p: T => Boolean): Boolean = {
while (hasNext) {
if (p(next())) return true
}
false
}
def foldLeft[U](x: U)(f: (U, T) => U): U = {
var acc = x
while (hasNext) acc = f(acc, next())
acc
}
}foreach, after iterations the supplied function has been applied in order to exactly the first entries. For exists, every consumed entry has failed the predicate unless the method is returning true. For the left fold, the loop invariant after consuming entries isEach iteration extends the expression by the next entry on the right. For a finite remaining sequence, its unconsumed length is a common loop variant. ThusAn empty iterator invokes no callback, gives false for exists, and returns from the left fold. On an infinite iterator, exists can terminate when it finds a match; the other two operations ordinarily do not terminate. With constant-cost callbacks, finite input of length takes time complexity and constant auxiliary space.Maintain a stack of values of the complete subexpressions encountered so far, with the newest value at its head:The left fold processes tokens in their order. A number pushes its own value; an operator replaces the two latest subexpression values by their combination. The top value is the right operand, so preserving the order in
evalRP :: RPolish -> Int
evalRP = finish . foldl push []
where
push :: [Int] -> Elem -> [Int]
push stack (Number n) = n : stack
push (right:left:stack) (Operator op) =
applyOp op left right : stack
push _ (Operator _) = error "missing operand"
finish :: [Int] -> Int
finish [value] = value
finish _ = error "malformed expression"applyOp op left right is necessary for subtraction and division. Induction on the consumed token prefix proves this stack machine invariant. A complete valid expression finishes with exactly one value.Implement the three consumers directly with while loops. These methods consume the receiver; For
exists stops immediately after the first witness:trait RichIter[T] extends Iter[T] {
def foreach(f: T => Unit): Unit = {
while (hasNext) f(next())
}
def exists(p: T => Boolean): Boolean = {
while (hasNext) {
if (p(next())) return true
}
false
}
def foldLeft[U](x: U)(f: (U, T) => U): U = {
var result = x
while (hasNext) result = f(result, next())
result
}
}foreach, the loop invariant is that f has been called once, in order, on exactly the consumed prefix. For exists, provided it has not returned, every consumed entry fails the predicate; a returned true has a witness, while exhaustion proves there is none. For foldLeft, after consumed entries the loop invariant iswith result = x at . Thus initialization, one further application, and exhaustion prove the required left fold. On finite inputs, the remaining length is a loop variant for each loop. Callbacks are assumed not to mutate this iterator independently.With constant-cost callbacks and iterator operations, full consumption costs ; exists may return earlier. Empty inputs respectively do nothing, return false, and return x. Infinite inputs need not terminate, except that exists terminates upon reaching a witness.Use structural induction on the finite list
xs, with the assertion quantified over every accumulator e and every list ys. The equations of the left fold are foldl f e [] = e and foldl f e (x:xs) = foldl f (f e x) xs.For The third equality uses the induction hypothesis with accumulator
xs = [], both sides reduce to foldl f e ys. For the constructor case, equational reasoning givesfoldl f e ((x:xs) ++ ys)
= foldl f e (x : (xs ++ ys))
= foldl f (f e x) (xs ++ ys)
= foldl f (foldl f (f e x) xs) ys
= foldl f (foldl f e (x:xs)) ysf e x. Hence the stated identity holds. No inspection of ys was required: in Haskell this equality also permits infinite or partially defined ys, with both expressions denoting the same possibly undefined result.Again use structural induction on the finite list. At The penultimate equality uses the induction hypothesis. Thus
[], both the right fold and the left fold return e. For x:xs, use reverse (x:xs) = reverse xs ++ [x], part (a), and the definition of flip:foldl (flip f) e (reverse (x:xs))
= foldl (flip f) e (reverse xs ++ [x])
= foldl (flip f) (foldl (flip f) e (reverse xs)) [x]
= flip f (foldl (flip f) e (reverse xs)) x
= f x (foldl (flip f) e (reverse xs))
= f x (foldr f e xs)
= foldr f e (x:xs)foldr f e xs = foldl (flip f) e (reverse xs). Finiteness matters: reversing an infinite list does not produce its first element, whereas some right folds do.Use the right fold definition Set The derived Haskell definition is thereforeEach step prepends the next element to the accumulator. This is a left fold derivation from list concatenation, rather than merely a proposed implementation.
xs ++ ys = foldr (:) ys xs, the right-identity law xs ++ [] = xs, and the finite-list involution law reverse (reverse xs) = xs. The last two laws are the additional results used here. Part (b) now givesxs ++ ys
= foldr (:) ys xs
= foldl (flip (:)) ys (reverse xs)ys = [] to obtain xs = foldl (flip (:)) [] (reverse xs). Substitute reverse xs for xs and simplify the double reversal:reverse xs
= foldl (flip (:)) [] (reverse (reverse xs))
= foldl (flip (:)) [] xsreverse :: [a] -> [a]
reverse = foldl (flip (:)) []Separate the maximal decimal prefix from the unconsumed suffix, rejecting an empty prefix:The left fold uses the positional notation recurrence . This parses unsigned decimal operands as illustrated, leaving the first nondigit and everything after it untouched. As the required result type is
import Data.Char (isDigit, digitToInt)
type Parse a = String -> Maybe (a,String)
parseInt :: Parse Int
parseInt input =
case span isDigit input of
([],_) -> Nothing
(ds,ys) -> Just (foldl (\n d -> 10*n + digitToInt d) 0 ds, ys)Int, correct mathematical values require the parsed integer to fit that bounded type; arbitrary-length exact values would instead need Integer or an explicit integer overflow check.The most general type signature is
scanl :: (b -> a -> b) -> b -> [a] -> [b]. The left fold step consumes an accumulator of type b and an input of type a, returning the next accumulator. A left scan retains all these accumulator values, including the initial one.foldl f e (x:ys) = foldl f (f e x) ysFor the empty list, the prefix definition immediately gives
scanl f e [] = [e]. For a nonempty list, calculate:scanl f e (x:xs)
= map (foldl f e) ([] : map (x:) (inits xs))
= e : map ((foldl f e) . (x:)) (inits xs)
= e : map (foldl f (f e x)) (inits xs)
= e : scanl f (f e x) xsThe second-to-third line uses the displayed fold equation as an equality of functions of
ys. Hence the efficient left scan is:scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl f e [] = [e]
scanl f e (x:xs) = e : scanl f (f e x) xsOn a finite input of length , fully demanding the original prefix-fold results performs accumulator updates. The recurrence performs . Thus the update count improves from to , assuming constant-cost updates. Both return results. This does not assert constant space for arbitrary accumulators or imply that lazy accumulators are evaluated strictly.
These methods consume the receiver's remaining sequence;
exists stops as soon as it finds a witness:trait RichIter[T] extends Iter[T] {
def foreach(f: T => Unit): Unit = {
while (hasNext) f(next())
}
def exists(p: T => Boolean): Boolean = {
while (hasNext) {
if (p(next())) return true
}
false
}
def foldLeft[U](x: U)(f: (U,T) => U): U = {
var result = x
while (hasNext) result = f(result, next())
result
}
}After consumed elements,
foreach has invoked its callback on exactly that prefix, exists has found no witness in it unless it has already returned, and the left fold accumulator is the fold of that prefix in its original order. These loop invariants prove the finite-sequence results. On an infinite sequence, exists may still terminate when it reaches a witness; a full traversal or fold generally does not. To retain the original cursor, a caller can invoke the operation on a suitable copy.The right fold replaces the two list constructors by its two arguments; the left fold instead updates an accumulator while traversing the list.
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr c z [] = z
foldr c z (x:xs) = c x (foldr c z xs)
foldl :: (b -> a -> b) -> b -> [a] -> b
foldl s a [] = a
foldl s a (x:xs) = foldl s (s a x) xsThus
foldr is the natural list fold: it preserves the constructor arrangement while replacing [] by z and (:) by c. In particular, foldr (:) [] = id. More generally, the fold factorisation criterion says that the defining equations characterize the corresponding structural recursion. Association and lazy evaluation are separate: the accumulator in this definition of left fold is not automatically evaluated at each step.[ref]Haskell 2010 Language Report. Chapter 9, PreludeList: foldr and foldl
For every accumulator , pattern matching makes
foldl s a undefined the bottom value. Now use structural induction on a finite list prefix ending in the bottom value. The induction step is foldl s a (x:ps) = foldl s (s a x) ps; the induction hypothesis applies to every accumulator, including s a x. Consequently every such finite approximation has result .An infinite lazy list is the limit of its finite prefixes, each interpreted as a finite approximation of a lazy list. Definable Haskell operations are Scott continuous maps, so the result on the infinite lazy list is the supremum of the results on these approximations. Every result is , hence
foldl s a xs = undefined on every infinite input spine, irrespective of whether s would inspect the accumulator.For a concrete separation, choose
s = (&&), a = True, and xs = False : repeat True. The left fold is , whereas the right fold returns False after observing the first element: False && r does not demand r. It is reaching the end of the input spine, rather than strictness of the combining operation, that prevents this left fold from returning.