Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
Introduction
In the last episode on algebraic data types we started to get a glimpse of what it means to see algebraic structure in the Swift type system. We saw that forming structs corresponds to a kind of multiplication of the types inside the struct. Then we saw that forming enums corresponded to a kind of summation of all the types on the inside. And finally we used this intuition to figure how to properly model a datatype so that impossible states are not representable, and enforced by the compiler.
In this episode we are we are going to look at the next piece of algebra that is not captured by just plain sums and products: exponentiation. We will see that it helps build our intuition for how function arrows act with respect to other constructions, and even allow us to understand what makes a function more or less complicated.
Subscribe to Point-Free
Access this episode, plus all past and future episodes when you become a subscriber.
Already a subscriber? Log in
Exercises
Prove the equivalence of
1^a = 1
as types. This requires re-expressing this algebraic equation as types, and then defining functions between the types that are inverses of each other.What is
0^a
? Prove an equivalence. You will need to considera = 0
anda != 0
separately.How do you think generics fit into algebraic data types? We’ve seen a bit of this with thinking of
Optional<A>
asA + 1 = A + Void
.Show that sets with values in
A
can be represented as2^A
. Note thatA
does not require anyHashable
constraints like the Swift standard librarySet<A>
requires.Define
intersection
andunion
functions for the above definition of set.How can dictionaries with keys in
K
and values inV
be represented algebraically?Implement the following equivalence:
func to<A, B, C>(_ f: @escaping (Either<B, C>) -> A) -> ((B) -> A, (C) -> A) { fatalError() } func from<A, B, C>(_ f: ((B) -> A, (C) -> A)) -> (Either<B, C>) -> A { fatalError() }
Implement the following equivalence:
func to<A, B, C>(_ f: @escaping (C) -> (A, B)) -> ((C) -> A, (C) -> B) { fatalError() } func from<A, B, C>(_ f: ((C) -> A, (C) -> B)) -> (C) -> (A, B) { fatalError() }