A blog exploring functional programming and Swift.

Open Sourcing Gen

Monday Mar 18, 2019

Today we are open sourcing Gen: a lightweight wrapper around Swift’s randomness API’s that makes randomess more composable, transformable and controllable!

We are excited to announce the 0.1.0 release of Gen, a new API for expressing randomness in Swift. Its focus is on composability (combining multiple forms of randomness into new forms of randomness), transformability (applying functions to randomness), and controllability (deterministic pseudo-randomness for times we need it). With these three features you can break down large, complex forms of randomness into smaller, simpler pieces, and you can write tests for it!


Swift’s randomness API is powerful and simple to use. It allows us to create random values from many basic types, such as booleans and numeric types, and it allows us to randomly shuffle arrays and pluck random elements from collections.

However, it does not make it easy for us to extend the randomness API. For example, while it may gives us ways of generating random booleans, numeric values, and even ways to shuffle arrays and pluck random elements from arrays, it says nothing about creating random strings, random collections of values, or random values from our own data types.

Further, the API is not very composable, which would allow us to create complex types of randomness from simpler pieces. One primarily uses the API by calling static random functions on types, such as Int.random(in: 0...9), but there is no guidance on how to generate new types of randomness from existing randomness.


Gen is a lightweight wrapper over Swift’s randomness APIs that makes it easy to build custom generators of any kind of value. Most often you will reach for one of the static variables inside Gen to get access to a Gen value:

Gen.bool // Gen<Bool>

Rather than immediately producing a random value, Gen describes a random value that can be produced by calling its run method:

let myGen = Gen.bool // Gen<Bool>

myGen.run() // true
myGen.run() // true
myGen.run() // false

Every random function that comes with Swift is also available as a static function on Gen:

// Swift's API
Int.random(in: 0...9) // 4

// Gen's API
Gen.int(in: 0...9).run() // 6

The reason it is powerful to wrap randomness in the Gen type is that we can make the Gen type composable. For example, a generator of integers can be turned into a generator of numeric strings with a simple application of the map function:

let digit = Gen.int(in: 0...9)           // Gen<Int>
let stringDigit = digit.map(String.init) // Gen<String>

stringDigit.run() // "7"
stringDigit.run() // "1"
stringDigit.run() // "3"

Already this is a form of randomness that Swift’s API’s do not provide out of the box.

Gen provides many operators for generating new types of randomness, such as map, flatMap and zip, as well as helper functions for generating random arrays, sets, dictionaries, string, distributions and more! A random password generator, for example, is just a few operators away.

// Take a generator of random letters and numbers.
let password = Gen.letterOrNumber
  // Generate 6-character strings of them.
  .string(of: .always(6))
  // Generate 3 segments of these strings.
  .array(of: .always(3))
  // And join them.
  .map { $0.joined(separator: "-") }

password.run() // "9BiGYA-fmvsOf-VYDtDv"
password.run() // "dS2MGr-FQSuC4-ZLEicl"
password.run() // "YusZGF-HILrCo-rNGfCA"

But composability isn’t the only reason the Gen type shines. By delaying the creation of random values until the run method is invoked, we allow ourselves to control randomness in circumstances where we need determinism, such as tests. The run method has an overload that takes a RandomNumberGenerator value, which is Swift’s protocol that powers their randomness API. By default it uses the SystemRandomNumberGenerator, which is a good source of randomness, but we can also provide a seedable “pseudo” random number generator, so that we can get predictable results in tests:

var lcrng = LCRNG(seed: 0)
Gen.int(in: 0...9).run(using: &lcrng) // "8"
Gen.int(in: 0...9).run(using: &lcrng) // "1"
Gen.int(in: 0...9).run(using: &lcrng) // "7"

lcrng.seed = 0
Gen.int(in: 0...9).run(using: &lcrng) // "8"
Gen.int(in: 0...9).run(using: &lcrng) // "1"
Gen.int(in: 0...9).run(using: &lcrng) // "7"

This means you don’t have to sacrifice testability when leveraging randomness in your application.

Learn more

The Gen type has been explored on Point-Free numerous times. We began by showing that randomness can be made composable by expressiong it as a function. This allowed us to define map, flatMap and zip operations on randomness, which helped us create very complex forms of randomness for just a few small, simple pieces.

In order to show just how powerful composable randomness is, we wrote a blog post demonstrating how to create a Zalgo text generator. This consisted of defining small generators that do a specific thing, such as generating special unicode characters, and the piecing them together to finally give us the generator that allows us to create bizarre strings such as: P̵̙̬̬̝̹̰̜ͧ̿o̎ĩͪͪ͗n͓̪̝̓t̊̏̾̊̆-̦̲̥͉F̠͖͈̮̾́ͨ͐͝r̸͋̆̅̅ͪ̚ë̝͑ͣ̒̏̈́̉e̟̺̪͕̹͆ͩͯ̑ͣ͂̉.

Then we showed how randomness can be made controllable (part 1 and part 2) by slightly tweaking Gen definition so that it took a RandomNumberGenerator, which is the Swift protocol that powers all of Swift’s randomness API’s. This allowed us to keep all of Gen‘s nice compositional properties while also allowing us to plug in our own random number generators. In particular, we can use a deterministic, seedable, pseudo-random number generator in tests so that we can still test code that invokes randomness API’s.

Try it out today!

The official 0.1.0 release of Gen is on GitHub now, and we have more improvements and refinements coming soon. We hope that Gen will help you control the complexity in your applications that arises from randomness, both by making the randomness simpler to understand and easier to test.

Announcing swift-html 0.2.0

Tuesday Jan 8, 2019

Today we’re releasing our first minor update to swift-html, a Swift DSL for type-safe, extensible, and transformable HTML documents. In fact, this very page was rendered with it!

We’ve been battle-testing this library for awhile now, long before its initial release last September. Today’s release contains a number of new features and fixes, including several patches from the community!

Support for new platforms and dependency managers

While we imagined swift-html to be most useful on the server with server-side Swift becoming more and more popular, a pull request let us know that there was interest in using our library on iOS, as well! With the help of the community we now support being embedded in your iOS, tvOS, and watchOS apps. Now you can render HTML in a type-safe manner just about anywhere!

We’ve also made installing swift-html on these platforms easier than ever by adding support for Carthage and CocoaPods. Check out the installation instructions to get started.


We’ve added a new debugRender function that will render HTML nodes in a more human-readable format by indenting each node.

let doc = html([
    p(["You’ve found our site!"])

// <html><body><h1>Welcome!</h1><p>You’ve found our site!</p></body></html>

// <html>
//   <body>
//     <h1>
//       Welcome!
//     </h1>
//     <p>
//       You’ve found our site!
//     </p>
//   </body>
// </html>

While this rendering format is not suitable for the browser (it can introduce additional, unwanted whitespace), it’s perfect for reading and snapshot testing.


Speaking of snapshot testing, swift-html now comes with a helper module, HtmlSnapshotTesting!

A couple months ago we had our first official release of SnapshotTesting, a library that lets you snapshot test not only UIViews to images, but any value to any format. We’ve been snapshot testing the HTML of the Point-Free web site since day one, so we’re excited to make this kind of testing easier for everyone.

You can snapshot test swift-html’s Node type using the html strategy.

import Html
import HtmlSnapshotTesting
import SnpashotTesting
import XCTest

class MyWebPageTests: XCTestCase {
  func testMyWebPage() {
    let doc = html([
        p(["You’ve found our site!"])

    // Assert against an HTML reference on disk
    assertSnapshot(matching: doc, as: .html)

Bug fixes and performance improvements

This release also contains a few bug fixes from the community and free rendering performance improvements thanks to a heavy dose of inout.

To give swift-html a try today, check out its GitHub page.

2018 Year-in-Review

Wednesday Dec 19, 2018

We launched on January 29 of this year, and next month are approaching our one year anniversay. In that time we have released 41 episodes with over 19 hours of video (9 of which are free for all), published 25 blog posts, served over 36,000 unique visitors, and open sourced 8 (!) libraries from the topics covered in our episodes! We’re really proud of everything we produced for 2018, so join us for a quick review of some of our favorite highlights.


We produced 41 episodes this year, about one every 1.2 weeks. We covered a broad set of topics, from the foundational ideas that somehow come up again-and-again, to the more practical, down-to-earth ideas that you can immediately bring into your code base today. The balance of these two sides is important because without the practical episodes it is hard to see the forest from the trees, and without the abstract episodes we’d be stuck in an endless loop of adding superficial niceties to our code that don’t meaningfully improve it in a significant way.

Here’s a small selection of some of our favorite episodes from the past year:

Protocol Witnesses

We ended the year with a bang! We’ve spent nine whole episodes rethinking the community best-practice of “protocol-oriented programming”. We started our series on “protocol witnesses” by showing how many basic protocol features and functionality can be implemented using just concrete data types and functions. We even showed that this translation is completely mechanical: that given any protocol, there is a clear path to defining a data type equivalent (part 1, part 2).

We then dove into some of the more advanced features of protocols (part 1, part 2), some of which we only got recently, like conditional conformance. We saw how these features manifest in the “protocol witness” world as plain ole functions. With witnesses we we didn’t have to wait. We were able to take advantage of conditional conformance with the very first version of Swift.

We wrapped things up with four down-to-earth episodes where we tool a real-world library, abstracted it to work with protocols (part 1, part 2), reabstracted it to work with witnesses, and finally fixed a problem with the libary that prevented it from working on asynchronous values.


We spent several episodes diving deep into the zip function. While many of us are aware of zip on arrays and may have even reached for it on occasion, it may be surprising that zip appears on structures almost as often as map! The implications are perhaps even more interesting. We saw that zip on optionals mirrors optional sugar that we’re used to with if-let binding. We saw that zip on the result type made us question the structure of the result type itself. And we saw that zip on an asynchronous type was a natural way to think about parallelism.

Zip has popped up in a number of our open source libraries, including swift-overture and swift-validation.


The Tagged type provides a lightweight wrapper around any type so that you can safely distinguish between, say, an Int-based user id and an Int-based blog post id. It uses a phantom generic and some powerful Swift features, like conditional conformance, to make it easy to make your code safer.

We even open sourced our own implementation, swift-tagged, to make it easy to take advantage of in your code base. The Point-Free web site makes heavy use of Tagged, and it’s prevented quite a few bugs from going out in deploys! 😅

UIKit Styling

In our 3rd of 41 episodes we showed that composition was truly applicable to everyday code. It’s still one of our most popular episodes to date!

There are many different ways to combine and reuse styling logic for iOS views, but we showed that plain ole functions are the simplest solution.

Later on in the year we revisited UIKit styling using our swift-overture library, allowing us to introduce the concept of composing styling functions without the need for operators, and with the addition of some expressive setter functions using Swift key paths.


We’ve had several episodes on managing dependencies using Environment so far and we have more to come. It’s one of the easiest ways to understand where dependencies are lurking in your code and make these untestable parts of your code base fully testable.

Stephen further spread the word at a talk this year at NSSpain, which we made available in blog form soonafter.

Open Source

We knew we wanted to do as much of Point-Free in the open as possible, so this very site has been open source from the very beginning. We built this site from first principles in a functional style, writing each component as open source along the way.

Since our launch, we even open sourced libraries from the content in our episodes: 8 in total! And 4 of these libraries has a home in the official Swift Source Compatibility Suite. Each of these libraries aims to solve a single problem in the simplest way possible in order to minimize the cost of bringing the dependency into your project.

Our open source work has accrued over 3,800 stars on GitHub! We’re so thankful that the community has expressed such an interest!


Our most recently open sourced library, swift-snapshot-testing, takes snapshot testing to the next level. It allows you to snapshot test any kind of data type into any kind of format. For example, you can snapshot test UIViews and UIViewControllers into an image format, which is typical of these kinds of libraries, but you can also snapshot those objects into a textual format so that you can see the whole view hierarchy. And this kind of snapshot testing isn’t limited to UI! You can snapshot any value into any format using a number of strategies that ship with the library, or you can define new strategies yourself!

The design of this library was covered in a whopping 9 episodes


Server-side Swift is still in its nascent stages, but there have been some promising developments in the field, such as the Swift NIO project. Currently the most popular way to render HTML pages in server-side Swift is with templating languages, but there are a lot of problems with templates. We open sourced the swift-html library to remedy these problems by providing a first-class data type to represent HTML and a way to render that data to an HTML string that can be sent to the browser. In fact, this library powers the HTML rendering of this very site!

The design of this library was covered in 4 episodes:

swift-html-kitura, swift-html-vapor

The two most popular server-side Swift frameworks are Kitura and Vapor, but both use templating languages as the default way to render HTML. Luckily each framework provides a way to use your own view layer, and so both swift-html-kitura and swift-html-vapor are small libraries to help you use our swift-html library in either framework.


Functional programming tends to make heavy use of custom operators, and this is because infix notation and associativity are a powerful way of reducing clutter in an expression and exposing some really interesting algebraic properties. But, it’s not for everyone. So, we open sourced swift-overture to be a simple library that gives you access to lots of interesting function composition tools, without the use of operators. We discussed this idea in the following episode:


After covering the Tagged type in an episode, we open sourced swift-tagged to make it easier for everyone to benefit from this powerful type.


An adage of functional programmers is “make invalid states unrepresentable”. This means that states of data that shouldn’t be allowed to happen should actually be provable by the compiler as being impossible. We achieve this by using concepts from algebraic data types in order to chisel away the invalid values from our types, and are hopefully only left with the valid states. Our swift-nonempty library applies these ideas to model a “non-empty collection” type, which allows you to transform any collection type into a non-empty version of itself. We covered the design of this library in 4 episodes:


Swift error handling is built around Optional, Result, and throws. These constructs allow us to write a sequence of failable instructions to Swift and return nil, failure, or throw an error to short-circuit things and bail out of the happy path.

This correspondence between Optional, Result, and throws is interesting on its own, but we spent several episodes exploring the zip function beyond its usualy definition on arrays, and we discovered something interesting: zip gives us the ability to accumulate multiple errors when more than one input is invalid, a common thing we want with form data, and something that short-circuiting throws can’t do.

To make this functionality available to everyone, we open sourced Validated, a Result-like type that can accumulate multiple errors.

Here’s to 2019!

Thanks for joining us on the first year of our journey! We have great material for 2019 and hope to see you then.

Until next year!

Older blog posts

Wednesday Dec 19, 2018

Save 30% on Point-Free

To end 2018 on a high note we're offering a 30% discount to new subscribers for their first year. Just click through to read the full post below! We hope you'll join us for all of the great material we have planned for 2019.

Monday Dec 3, 2018

SnapshotTesting 1.0: Delightful Swift snapshot testing

Today we are open sourcing SnapshotTesting 1.0: a modern, composable snapshot testing library built entirely in Swift!

Monday Oct 29, 2018

Some news about contramap

We've seen that contramap is a powerful operation, but the name isn't fantastic. We propose a much more intuitive name for this operation, and in doing so make our code much easier to read.

Tuesday Oct 9, 2018

How to Control the World

APIs that interact with the outside world are unpredictable and make it difficult to test and simulate code paths in our apps. Existing solutions to this problem are verbose and complicated, so let's explore a simpler solution by embracing singletons and global mutation, and rejecting protocol-oriented programming and dependency injection.

Monday Oct 8, 2018

Watch episodes in your favorite podcast app!

Follow along with the newest Point-Free episodes using your favorite podcast app. We now support podcast-friendly RSS feeds for viewing all of our videos.

Thursday Sep 20, 2018

Random Zalgo Generator

Let's create a random Zalgo text generator using the simple Gen type we defined in this week's episode!

Thursday Sep 13, 2018

Type-safe HTML with Kitura

Today we're releasing a Kitura plug-in for rendering type-safe HTML. It provides a Swift compile-time API to HTML that prevents many of the runtime errors and vulnerabilities of traditional templated HTML rendering.

Thursday Sep 13, 2018

Type-safe HTML with Vapor

Today we're releasing a Vapor plug-in for rendering type-safe HTML. It provides a Swift compile-time API to HTML that prevents many of the runtime errors and vulnerabilities of traditional templated HTML rendering.

Wednesday Sep 12, 2018

Open sourcing swift-html: A Type-Safe Alternative to Templating Languages in Swift

Today we are open sourcing a new library for building HTML documents in Swift. It's extensible, transformable, type-safe, and provides many benefits over templating languages.

Friday Aug 17, 2018

Overture 0.3.0: Now with Zip

Today we are releasing Overture 0.3.0 with a bunch of useful zip functions.

Friday Aug 17, 2018

Open Sourcing Validated

Today we are open sourcing Validated, a tiny functional Swift library for handling multiple errors: functionality that you don't get from throwing functions and the Result type.

Thursday Aug 16, 2018

Solutions to Exercises: Zip Part 3

Today we solve the exercises to the third and final part of our introductory series on zip.

Wednesday Aug 15, 2018

Solutions to Exercises: Zip Part 2

Today we solve the exercises to the second part of our introductory series on zip.

Tuesday Aug 14, 2018

Solutions to Exercises: Zip Part 1

Today we solve the exercises to the first part of our introductory series on zip.

Monday Aug 6, 2018

Announcing Student Discounts

Get 50% off your Point-Free subscription with proof of enrollment at a university or coding school.

Monday Jul 30, 2018

Celebrating 6 Months

This week marks 6 months since our launch, and we’re making one of our most popular episodes free to the public!

Monday Jul 2, 2018

Conditional Coding

What happens when we combine Swift's conditional conformance with codability?

Monday Jun 25, 2018

Open Sourcing NonEmpty

Today we are open sourcing NonEmpty, a Swift library for modeling non-empty collection types. This small library can help make your code safer and more expressive with very little work.

Monday Jun 18, 2018

Tagged Seconds and Milliseconds

Let's create a type-safe interface for dealing with seconds and milliseconds in our programs. We'll use the `Tagged` type, which allows us to construct all new types in a lightweight way.

Wednesday May 30, 2018

Styling with Functions: Free for Everyone!

We are making one of our early episodes, “UIKit Styling with Functions”, free to everyone today! It’s a seminal episode that sets the foundation for some later work in the Point-Free series.

Tuesday May 15, 2018

Overture: Now with Functional Setters

Announcing Overture 0.2.0! This release is all about setters: functions that allow us to build complex transformations out of smaller units.

Monday May 7, 2018

Solutions to Exercises: Contravariance

This week we solve the exercises from our episode on contravariance, because there were _a lot_ of them!

Monday Apr 23, 2018

Case Study: Algebraic Data Types

Let’s look at a real world use for algebraic data types. We will refactor a data type that is used in the code on this very site so that the invalid states are unrepresentable by the compiler.

Monday Apr 23, 2018

Announcing Point-Free Pointers!

Today we are excited to announcement launch of Point-Free Pointers, a blog to supplement our video series for all the content we couldn’t fit in. Expect to find regularly postings here that dive even deeper into functional programming, showing real world use cases and more!