Blog

Functional Snippet #1: Decomposing Arrays

The following snippet decomposes an array into a tuple containing the first element, and the rest of the array. If the array is empty, it returns nil:

extension Array {
    var decompose : (head: T, tail: [T])? {
        return (count > 0) ? (self[0], Array(self[1..<count])) : nil 
    }
}

This is very useful when you combine it with if let statements or pattern matching. For example, here is a recursive definition of sum:

func sum(xs: [Int]) -> Int {
    if let (head, tail) = xs.decompose {
        return head + sum(tail) 
    } else {
        return 0 
    }
}

You can easily define your own decomposing functions on other types, such as dictionaries or strings.

Stay up-to-date with our newsletter or follow us on Twitter.

Back to the Blog

recent posts