Refactoring with Monoids and Sum Types — Part 1

Matthias
Matthias
May 7, 2017 · 9 min read


data class Item(val obj: GameObject)
val inventory: Array<Item>(size = 9) { null }
inventory[0] = Item(pickaxe)
inventory[1] = Item(sword1)
inventory[2] = Item(sword2)

fun move(inventory: Array<Item>, from: Int, to: Int) {
val item = inventory[from]
inventory[from] = null
if (inventory[to] == null) {
inventory[to] = item
} else {
TODO()
}
}
fun move(inventory: Array<Item>, from: Int, to: Int) {
...
else {
val other = inventory[to]
if (other is Set) {
// add item to stack
inventory[to] = other + item
} else {
// create new stack
inventory[to] = setOf(other, item) // NOPE!
}
}
}

e + e = e // two nothings combine to nothing
e + i = i // adding an item to nothing leaves us with the item
i + e = i // adding nothing to an item leaves us with the item
e + s = s // adding a stack to nothing leaves us with a stack
s + e = s // adding nothing to a stack leaves us with a stack
i + i = s // adding two items creates a new stack
s + s = s // adding two stacks creates a larger stack
 (i + i) + e = i + (i + e)

val inventory = Array<Set<Item>>(size = 9) { emptySet() }fun move(inventory: Array<Set<Item>>, from: Int, to: Int) {
inventory[to] = inventory[to] + inventory[from]
inventory[from] = emptySet()
}
inventory.fold(emptySet()) { a: Set<Item>, b: Set<Item> -> a + b }

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade