# <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> Folds :fa fa-question-circle: Changing the parameter type ```scala def foldLeft (xs:List[List[Int]], z:String, f:(String,List[Int])=>String) : String = xs match case Nil => z case x::rest => foldLeft (rest, f(z, x), f) val xss = List( List(11,21,31), List(), List(41,51) ) foldLeft (xss, "[", _ + " " + _.length) + " ]" ``` <div class="text-sm"> ```scala res1: Int = "[ 3 0 2 ]" ``` </div> ---
# <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