Using with to Compose Uncertain Structures

Let’s learn how to use the with function to help us in carrying out pattern matching.

The logic of using with

The philosophy of with is simple. It allows us to specify pattern matches at each step of composition:

  • If the match succeeds, the composition proceeds.

  • If it fails, the composition halts and falls through to an else condition.

Here’s an example from later in this chapter:

  • We will build an API layer that has to validate data.

  • The functions will have to have unappealing if-then logic rather than simple compositions.

  • We’ll use with to smooth out the rough edges.

Here’s how the approach works. First, let’s say we’re building a new quiz with data provided by the user. We want to pass validated data to a service that stores quizzes like this:

Get hands-on with 1200+ tech skills courses.