Functional Snippet #4: Flattening and Mapping Arrays

In functional programming, map on arrays is a common operation. Surprisingly often, the result of map is an array of arrays that needs to be flattened. In many functional languages, there is an operator defined for flattening, and then mapping. This operator is sometimes called bind. It maps a function f, and then flattens the resulting array of arrays into a single array:

infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
    return[], combine: +)

One cool use-case of this operator is combining multiple lists. For example, let’s say we have a list of ranks, and a list of suits:

let ranks = ["A", "K", "Q", "J", "10",
             "9", "8", "7", "6", "5", 
             "4", "3", "2"]
let suits = ["β™ ", "β™₯", "♦", "♣"]

Now, we can generate a list of all playing cards by enumerating all the ranks, and for each rank, combine them with each possible suit:

let allCards =  ranks >>= { rank in
    suits >>= { suit in [(rank, suit)] }

// Prints: [(A, β™ ), (A, β™₯), (A, ♦), 
//          (A, ♣), (K, β™ ), ...

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

Back to the Blog

recent posts