Skip to content
Author: Tianle Yuan

Map, Filter and Reduce⚓︎

Map-Filter-Reduce are well known as Syntactic Sugar, which is a term for syntax changes in computer programming which make it easier for humans to code. Also, it is a Fan-in Fan-out way to process multiple tasks.

Grammar⚓︎

Text Only
map(function(type1 -> type1))
Text Only
filter (function(type1 -> bool))
Text Only
reduce(init_val(type3), function(type1, type 2-> type3))

Way1: Function⚓︎

Example⚓︎

image

Steven Luscher on Twitter

Code⚓︎

way1.swift
import Foundation

func cook(food: String) -> String {
    var transformedFood = ""

    switch food {
        case "🌽": 
            transformedFood = "🍿" 
            print(1)
        case "🐮": 
            transformedFood = "🍔"
            print(2)
        case "🐔": 
            transformedFood = "🍳"
            print(3)
    default: transformedFood = food // remains uncooked
    }

    return transformedFood
}

func eat(food1: String, food2: String) -> String {
    var transformedFood = "💩"
    return transformedFood
}

func isVegetarian(dish: String) -> Bool {
    return dish=="🍳"
}

//Map
let meals = ["🌽", "🐮", "🐔"].map(cook)
//Filter
let filtered_meals = meals.filter(isVegetarian)
//Reduce
let result = filtered_meals.reduce("",eat)
//Print
print(meals)
print(filtered_meals)
print(result)

Result⚓︎

image

Way2: Closure⚓︎

Example⚓︎

Realize the assert shown below with closure:

Q2.swift
for _ in 0...5 {
    let foodNames = ["🍔": "hamburger", "🍟": "french fries", "🌽": "popcorn"]

    var outcome = foodNames.map({...}).filter({}).reduce(...,{...})
    outcome.removeFirst()

    assert(
        outcome == "Hamburger Popcorn" ||
        outcome == "Popcorn Hamburger" 
    )
}

Code⚓︎

way2.swift
import Foundation

for _ in 0...5 {
    let foodNames = ["🍔": "hamburger", "🍟": "french fries", "🌽": "popcorn"]

    //Map
    var mapped = foodNames.map({(key,value) -> String in return value.capitalized})
    //Filter
    var filterred = mapped.filter({(food:String) -> Bool in return !(food == "French Fries")})
    //Reduce
    var reduced = filterred.reduce("",{a, b in a +  " " + b})

    reduced.removeFirst()
    var outcome = reduced

    assert(
        outcome == "Hamburger Popcorn" ||
        outcome == "Popcorn Hamburger" 
    )
}

Result⚓︎

image

Way3: Using the built-in operator⚓︎

Example⚓︎

Realize the assert shown below with built-in operator:

Q3.swift
let outcome = [2, 3, 5, 8].map({...}).filter({...}).reduce(...,...)

assert(outcome == 108)

Code⚓︎

way3.swift
import Foundation

let outcome = [2, 3, 5, 8].map( {$0 + 1} ).filter( {$0 != 5} ).reduce(1, *)

assert(outcome == 108)

Result⚓︎

image

Comments