1. What is functional programming?

The benefits of FP: A simple example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ASIS: A Kotlin program with side effects
class Cafe {
    fun buyCoffee(cc: CreditCard): Coffee {
        val cup = Coffee()
        cc.charge(cup.price)
        return cup
    }
}

// INPROGRESS: Adding a Payments object
class Cafe {
    fun buyCoffee(cc: CreditCard, p: Payments): Coffee {
        val cup = Coffee()
        p.charge(cc, cup.price)
        return cup
    }
}
1
2
3
4
5
6
7
// TOBE: 
class Cafe {
    fun buyCoffee(cc: CreditCard): Pair<Coffee, Charge> {
        val cup = Coffee()
        return Pair(cup, Charge(cc, cup.price))
    }
}
1
2
3
4
5
6
7
8
9
// Data class declaration with a constructor and immutable fields
data class Charge(val cc: CreditCard, val amount: Float) {
    fun combine(other: Charge) : Charge = 
    if ( cc == other.cc )
        Charge(cc, amount + other.amount)
    else throw Exception(
        "Cannot combine charges to different cards"
    )
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Cafe {
    fun buyCoffee(cc: CreditCard) : Pair<Coffee, Charge> = TODO()

    fun buyCoffees(
        cc: CreditCard,
        n: Int
    ): Pair<List<Coffee>, Charge> {
        val purchases: List<Pair<Coffee, Charge>> = List(n) { buyCoffee(cc)}
        val (coffees, charges) = purchases.unzip()
        return Pair(
            coffees,
            charges.reduce { c1, c2 -> c1.combine(C2) }
        )
    } 
}