Collection
Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
Introduction
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.
Subscribe to Point-Free
Access this episode, plus all past and future episodes when you become a subscriber.
Already a subscriber? Log in
Exercises
Create a function called
frequency
that takes an array of pairs,[(Int, Gen<A>)]
, to create aGen<A>
such that(2, gen)
is twice as likely to be run than a(1, gen)
.Extend
Gen
with anoptional
computed property that returns a generator that returnsnil
a quarter of the time. What other generators can you compose this from?Extend
Gen
with afilter
method that returns a generator that filters out random entries that don’t match the predicate. What kinds of problems may this function have?Create a
string
generator of typeGen<String>
that randomly produces a randomly-sized string of any unicode character. What smaller generators do you composed it from?Redefine
element(of:)
to work with anyCollection
. Can it also be redefined in terms ofSequence
?Create a
subsequence
generator to return a randomly-sized, randomly-offset subsequence of an array. Can it be redefined in terms ofCollection
?The
Gen
type hasmap
defined it, which, as we’ve seen in the past, allows us to consider whatzip
might look like. Definezip2
onGen
:func zip2<A, B>(_ ga: Gen<A>, _ gb: Gen<B>) -> Gen<(A, B)>
Define
zip2(with:)
:func zip2<A, B, C>(with f: (A, B) -> C) -> (Gen<A>, Gen<B>) -> Gen<C>
With
zip2
andzip2(with:)
defined, define higher-orderzip3
andzip3(with:)
and explore some uses. What functionality doeszip
provide ourGen
type?
References
Random Zalgo Generator
Brandon Williams • Tuesday Nov 20, 2018We 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.