Functional Digression at Work

One of my coworkers asked how to filter a list, but return the “pass” and “fail” items in separate lists. For example, filter takes some data and a condition, and returns a list of the items that pass the condition, but what if we returned two lists? One of my other coworkers came up with a neat solution using reduce, and I wrote something using generics. Here’s the operation I’m calling “fork”, implemented in Swift3.

import Foundation

func fork<T>(_ data: [T], completion: (T)->Bool) -> ([T],[T]) {
    var pass = [T]()
    var fail = [T]()
    for item in data {
        completion(item) ? pass.append(item) : fail.append(item)
    return (pass,fail)

var (pass, fail) = fork([0,1,2,3,4]) { $0 % 2 == 0 }

Leave a Reply

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