# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Fold Left vs. Fold Right <div class="grid grid-cols-2 gap-4"> <div> ```scala def foldLeft [Z,X] (xs:List[X], z:Z, f:((Z,X)=>Z)) : Z = xs match { case Nil => z case x::rest => foldLeft (rest, f(z,x), f) } ``` </div> <div> ```scala def foldRight [X,Z] (xs:List[X], z:Z, f:((X,Z)=>Z)) : Z = xs match { case Nil => z case x::rest => f (x, foldRight (rest, z, f)) } ``` </div> </div> - `foldLeft` is _tail recursive_: `return foldLeft (rest, f(z, x))` - apply `f` to the head and the accumulated result - recursive call on the tail - base case used with first element - `foldRight` is _recursive into an argument_: - `return f (x, foldRight (xs, z))` - recursive call on the tail - apply `f` to the head and result of recursion - base case used with last element ---
SP2425: 20min student activity, then 15min coding together activity