First Foray into ‘reduce’

After trying to coax a Closure into being a Protocol and failing I realized I could do what I’m trying to do with reduce. The basic idea, MIDI-wise, is to run a MIDI message through a set of filters, and capture what comes out the other end.

The below makes use of closures of type Int -> Int. Substitute MIDIMessage wherever you see an Int and you’ll get the idea. ‘6’ below would represent the original, unfiltered MIDI message.

let a = { return $0 + 1 }

let b = { return $0 * 2 }

let arr = [a, b]

let x = arr.reduce(6) { (val, f) in f(val) }

print(x)        // prints '14'

Leave a Reply

Your email address will not be published. Required fields are marked *