Spde → Fold

This sketch demonstrates a fold function. Did you see it folding? If not, click to make it fold again.

This browser does not have a Java Plug-in.
Get the latest Java Plug-in here.

size(465, 190)

def random_seq = (0 until width) map { (_, random(height)) }
var h: Seq[(Int, Float)] = random_seq
override def mouseClicked { h = random_seq }

def draw() {
  h foreach { case (x, h) => line(x, 0, x, h) }
  h = (h :\ List[(Int, Float)]()) {
    case ((x1, h1), Nil) => (x1, h1) :: Nil
    case ((x1, h1), (x2, h2) :: t) =>
      (x1, (h1 + h2) /2) :: (x2, h2) :: t

On initialization (or clicking) the sketch builds a sequence of width random numbers between 0 and height. The draw function (called 25 times per second, is the plan) paints a line for each element of the sequence, then reassigns it to a list created by right-folding (:\) the sequence. Each element’s height is the average of its last value and the new height to its right. The rightmost element retains its original value, which critically affects the output over time.

See More Examples