This episode is for subscribers only. To access it, and all past and future episodes, become a subscriber today!See subscription optionsorLog in
Sign up for our weekly newsletter to be notified of new episodes, and unlock access to any subscriber-only episode of your choosing!Sign up for free episode
Today we’re going to start a series of episodes on a topic that might not seem very functional: randomness.
Swift 4.2 introduces much-needed library support for randomness, which was designed from the ground up to be easier and safer to use than the existing available APIs. We’re going to take a look at some of the problems it was designed to solve and explore how we may have solved them in an alternate, functional API rooted in composition.
We’ll start by taking quick look at the original problems.
Create a function called
frequency that takes an array of pairs,
[(Int, Gen<A>)], to create a
Gen<A> such that
(2, gen) is twice as likely to be run than a
Gen with an
optional computed property that returns a generator that returns
nil a quarter of the time. What other generators can you compose this from?
Gen with a
filter method that returns a generator that filters out random entries that don’t match the predicate. What kinds of problems may this function have?
string generator of type
Gen<String> that randomly produces a randomly-sized string of any unicode character. What smaller generators do you composed it from?
element(of:) to work with any
Collection. Can it also be redefined in terms of
subsequence generator to return a randomly-sized, randomly-offset subsequence of an array. Can it be redefined in terms of
Gen type has
map defined it, which, as we’ve seen in the past, allows us to consider what
zip might look like. Define
func zip2<A, B>(_ ga: Gen<A>, _ gb: Gen<B>) -> Gen<(A, B)>
func zip2<A, B, C>(with f: (A, B) -> C) -> (Gen<A>, Gen<B>) -> Gen<C>
zip2(with:) defined, define higher-order
zip3(with:) and explore some uses. What functionality does
zip provide our
We apply the ideas of composable randomness to build a random Zalgo generator, which is a way to apply gitchy artifacts to a string by adding strange unicode characters to it. It shows that we can start with very simple, small pieces and then compose them together to create a really complicated machine.