Unlock This Episode
Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.
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
Create a function called
frequencythat takes an array of pairs,
[(Int, Gen<A>)], to create a
(2, gen)is twice as likely to be run than a
optionalcomputed property that returns a generator that returns
nila quarter of the time. What other generators can you compose this from?
filtermethod that returns a generator that filters out random entries that don’t match the predicate. What kinds of problems may this function have?
stringgenerator 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
subsequencegenerator to return a randomly-sized, randomly-offset subsequence of an array. Can it be redefined in terms of
mapdefined it, which, as we’ve seen in the past, allows us to consider what
zipmight 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
Random Zalgo GeneratorBrandon Williams • Tuesday Nov 20, 2018
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.