We’ll never know how many people were actually impressed by those one liners during social gatherings, but my guess is that at least for the uninitiated the more complex examples were a good incentive to learn more about functional programming.

Let’s see how Swift fares against the other languages, trying to solve the same 10 exercises using one liners, maybe obtaining something interesting in the process (see #6 and #10).

#1 Multiply each element of an array by 2

Not much to see in this first example, easily solvable using map as we all know.

(1...1024).map{$0 * 2}

#2 Sum a list of numbers

This exercise is solved using reduce and the plus operator, leveraging the fact that the plus operator is a function, but the solution is obvious, we’ll see in a moment a few more creative uses of reduce.

(1...1024).reduce(0,+)

#3 Verify if Exists in a String

Let’s verify if a tweet contains at least one of a few selected keywords using filter:

#6 Filter list of numbers

In this case we are asked to partition a sequence using a provided filtering function. Many languages have in addition to the usual map, flatMap, reduce, filter, etc… also a partitionBy function that does exactly that, Swift as you know doesn’t have something similar (the NSArray function that filters by NSPredicate is not what we want here).

Therefore, we could solve this extending Sequence with a partitionBy function that we’ll use to partition an integer array:

This is slightly better, but it traverses the sequence two times and trying to turn this into a one liner removing the enclosing function will get us something with too much duplicated stuff (the filtering function and the array that will be used in two places).

Can we build something that will transform the original sequence into a partition tuple using a single stream of data? Yes we can, using reduce.

What we are doing here is building the result tuple that contains the two partitions, an element at a time, testing each element of the original sequence using the filtering function and appending this element to the first or second partition array depending on the filtering result.

Finally a true one liner but notice that the fact that the partition arrays are being built via append will actually make it way slower than the two previous implementations.

#7 Fetch and Parse an XML web service

Some of languages above don’t rely on external libraries and have more than one option available by default to deal with XML (e.g. Scala that “natively” albeit awkwardly supports XML parsing into objects), but Foundation provides only the SAX parser NSXMLParser, and as you may have already guessed we are not going to use it.

There are a few alternative open source libraries we could use in this case, some of them written in C or Objective-C and others in pure Swift.

let xmlDoc = try? AEXMLDocument(xmlData: NSData(contentsOf: URL(string:"https://www.ibiblio.org/xml/examples/shakespeare/hen_v.xml")!)!)
if let xmlDoc=xmlDoc {
var prologue = xmlDoc.root.children[6]["PROLOGUE"]["SPEECH"]
prologue.children[1].stringValue // Now all the youth of England are on fire,
prologue.children[2].stringValue // And silken dalliance in the wardrobe lies:
prologue.children[3].stringValue // Now thrive the armourers, and honour's thought
prologue.children[4].stringValue // Reigns solely in the breast of every man:
prologue.children[5].stringValue // They sell the pasture now to buy the horse,
}

#8 Find minimum (or maximum) in a List

We have various ways to find the minimum and maximum of a sequence, among those the min and max functions:

//Find the minimum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].sorted().first
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.max, min)
[10,-22,753,55,137,-1,-279,1034,77].min()
//Find the maximum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].sorted().last
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.min, max)
[10,-22,753,55,137,-1,-279,1034,77].max()

#9 Parallel Processing

Some languages allows to enable in a simple and transparent way parallel processing of sequences for functionalities like map and flatMap, to speed up the execution of sequential and independent operations using thread pools under the hood.

#10 Sieve of Erathostenes

The good old sieve of Erathostenes is used to find all the prime numbers until a given upper limit n.

Starting with a sequence of all the integers smaller than n, the algorithm removes all the multiples of each integer, until we are left with just prime numbers. And to speed up the execution, we don’t actually need to check each integer for its multiple, we can just stop at the square root of n.

Based on that definition the first implementation could look like this:

We use the outer range to iterate over the integers we want to check and for each one we calculate a sequence of multiples of those numbers using stride(from:Int, to:Int, by:Int). Those sequences are then substracted from a Set initialized with all the integers from 2 to n.

But as you can see, to actually remove the multiples we use an external mutable Set, introducing a side-effect.

To eliminate side-effects, as we should always try to do, we will first calculate all the subsequences, flatMap them in a single array of multiples and remove these integers from the original Set.