O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Partitioning an array

We can use reduce to partition an array with a specific criterion. For instance, in the following example, we partition numbersToPartitionArray into two partitions, keeping all even numbers in the left partition:

func partition<T>(list: [T], criteria: (T) -> Bool) -> (lPartition: [T], rPartition: [T]) {     return list.reduce((lPartition: [T](), rPartition: [T]())) {         (accumlator: (lPartition: [T], rPartition: [T]), pivot: T) ->           (lPartition: [T], rPartition: [T]) in         if criteria(pivot) {             return (lPartition: accumlator.lPartition + [pivot],                    rPartition: accumlator.rPartition)         } else {             return (rPartition: accumlator.rPartition + [pivot],                    lPartition: accumlator.lPartition)         }     } } let doublesToPartition = [3.0, 4.0, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required