layout: post
title: “Understanding traverse and sequence”
description: “Mixing lists and elevated values”
categories: [“Patterns”]
seriesId: “Map and Bind and Apply, Oh my!”
seriesOrder: 4

image: “/assets/img/vgfp_sequence_stack.png”

This post is one in a series.
In the first two posts, I described some of the core functions for dealing with generic data types: map, bind, and so on.
In the previous post, I discussed “applicative” vs “monadic” style, and how to lift values and functions to be consistent with each other.

In this post, we’ll look at a common problem: working with lists of elevated values.

Series contents

Here’s a list of shortcuts to the various functions mentioned in this series:


Part 4: Mixing lists and elevated values

A common issue is how to deal with lists or other collections of elevated values.

Here are some examples:

  • Example 1: We have a parseInt with signature string -> int option, and we have a list of strings. We want to parse all the strings at once.
    Now of course we can use map to convert the list of strings to a list of options. But what we really want is not a “list of options” but an “option of list”,
    a list of parsed ints, wrapped in an option in case any fail.

  • Example 2: We have a readCustomerFromDb function with signature CustomerId -> Result<Customer>, that will return Success if the record
    can be found and returned, and Failure otherwise. And say we have a list of CustomerIds and we want to read all the customers at once.
    Again, we can use map to convert the list of ids to a list of results. But what we really want is not a list of Result<Customer>,
    but a Result containing a Customer list, with the Failure case in case of errors.

  • Example 3: We have a fetchWebPage function with signature Uri -> Async<string>, that will return a task that will download the page contents on demand.
    And say we have a list of Uriss and we want to fetch all the pages at once.
    Again, we can use map to convert the list of Uris to a list of Asyncs. But what we really want is not a list of Async,
    but a Async containing a list of strings.

Mapping an Option generating function

Let’s start by coming up with a solution for the first case and then seeing if we can generalize it to the others.

The obvious approach would be:

  • First, use map to turn the list of string into a list of Option<int>.
  • Next, create a function that turns the list of Option<int> into an Option<int list>.

But this requires two passes through the list. Can we do it in one pass?

Yes! If we think about how a list is built, there is a “cons” function (:: in F#) that is used to join the head to the tail.
If we elevate this to the Option world, we can use Option.apply to join a head Option to a tail Option using the lifted version of cons.

  1. let (<*>) = Option.apply
  2. let retn = Some
  3. let rec mapOption f list =
  4. let cons head tail = head :: tail
  5. match list with
  6. | [] ->
  7. retn []
  8. | head::tail ->
  9. retn cons <*> (f head) <*> (mapOption f tail)

NOTE: I defined cons explicitly because :: is not a function and List.Cons takes a tuple and is thus not usable in this context.

Here is the implementation as a diagram:

Understanding traverse and sequence - 图1

If you are confused as to how this works, please read the section on apply in the first post in this series.

Note also that I am explicitly defining retn and using it in the implementation rather than just using Some. You’ll see why in the next section.

Now let’s test it!

  1. let parseInt str =
  2. match (System.Int32.TryParse str) with
  3. | true,i -> Some i
  4. | false,_ -> None
  5. // string -> int option
  6. let good = ["1";"2";"3"] |> mapOption parseInt
  7. // Some [1; 2; 3]
  8. let bad = ["1";"x";"y"] |> mapOption parseInt
  9. // None

We start by defining parseInt of type string -> int option (piggybacking on the existing .NET library).

We use mapOption to run it against a list of good values, and we get Some [1; 2; 3], with the list inside the option, just as we want.

And if we use a list where some of the values are bad, we get None for the entire result.

Mapping a Result generating function

Let’s repeat this, but this time using the Result type from the earlier validation example.

Here’s the mapResult function:

  1. let (<*>) = Result.apply
  2. let retn = Success
  3. let rec mapResult f list =
  4. let cons head tail = head :: tail
  5. match list with
  6. | [] ->
  7. retn []
  8. | head::tail ->
  9. retn cons <*> (f head) <*> (mapResult f tail)

Again I am explicitly defining a retn rather than just using Success. And because of this, the body of the code for mapResult and mapOption is exactly the same!

Now let’s change parseInt to return a Result rather than an Option:

  1. let parseInt str =
  2. match (System.Int32.TryParse str) with
  3. | true,i -> Success i
  4. | false,_ -> Failure [str + " is not an int"]

And then we can rerun the tests again, but this time getting more informative errors in the failure case:

  1. let good = ["1";"2";"3"] |> mapResult parseInt
  2. // Success [1; 2; 3]
  3. let bad = ["1";"x";"y"] |> mapResult parseInt
  4. // Failure ["x is not an int"; "y is not an int"]

Can we make a generic mapXXX function?

The implementations of mapOption and mapResult have exactly the same code,
the only difference is the different retn and <*> functions (from Option and Result, respectively).

So the question naturally arises, rather than having mapResult, mapOption, and other specific implementations for each elevated type,
can we make a completely generic version of mapXXX that works for all elevated types?

The obvious thing would be able to pass these two functions in as an extra parameter, like this:

  1. let rec mapE (retn,ap) f list =
  2. let cons head tail = head :: tail
  3. let (<*>) = ap
  4. match list with
  5. | [] ->
  6. retn []
  7. | head::tail ->
  8. (retn cons) <*> (f head) <*> (mapE retn ap f tail)

There are some problems with this though. First, this code doesn’t compile in F#!
But even if it did, we’d want to make sure that the same two parameters were passed around everywhere.

We might attempt this by creating a record structure containing the two parameters, and then create one instance for each type of elevated world:

  1. type Applicative<'a,'b> = {
  2. retn: 'a -> E<'a>
  3. apply: E<'a->'b> -> E<'a> -> E<'b>
  4. }
  5. // functions for applying Option
  6. let applOption = {retn = Option.Some; apply=Option.apply}
  7. // functions for applying Result
  8. let applResult = {retn = Result.Success; apply=Result.apply}

The instance of the Applicative record (appl say) would be an extra parameter to our generic mapE function, like this:

  1. let rec mapE appl f list =
  2. let cons head tail = head :: tail
  3. let (<*>) = appl.apply
  4. let retn = appl.retn
  5. match list with
  6. | [] ->
  7. retn []
  8. | head::tail ->
  9. (retn cons) <*> (f head) <*> (mapE retn ap f tail)

In use, we would pass in the specific applicative instance that we want, like this:

  1. // build an Option specific version...
  2. let mapOption = mapE applOption
  3. // ...and use it
  4. let good = ["1";"2";"3"] |> mapOption parseInt

Unfortunately, none of this works either, at least in F#. The Applicative type, as defined, won’t compile. This is because F# does not support “higher-kinded types”.
That is, we can’t parameterize the Applicative type with a generic type, only with concrete types.

In Haskell and languages that do support “higher-kinded types”, the Applicative type that we’ve defined is similar to a “type class”.
What’s more, with type classes, we don’t have to pass around the functions explicitly — the compiler will do that for us.

There is actually a clever (and hacky) way of getting the same effect in F# though using static type constraints.
I’m not going to discuss it here, but you can see it used in the FSharpx library.

The alternative to all this abstraction is just creating a mapXXX function for each elevated world that we want to work with:
mapOption, mapResult, mapAsync and so on.

Personally I am OK with this cruder approach. There are not that many elevated worlds that you work with regularly, and even though you lose out on abstraction,
you gain on explicitness, which is often useful when working in a team of mixed abilities.

So let’s look at these mapXXX functions, also called traverse.


The traverse / mapM function

Common Names: mapM, traverse, for

Common Operators: None

What it does: Transforms a world-crossing function into a world-crossing function that works with collections

Signature: (a->E<b>) -> a list -> E<b list> (or variants where list is replaced with other collection types)

Description

We saw above that we can define a set of mapXXX functions, where XXX stands for an applicative world — a world that has apply and return.
Each of these mapXXX functions transforms a world-crossing function into a world-crossing function that works with collections.

Understanding traverse and sequence - 图2

And as we noted above, if the language supports type classes, we can get away with a single implementation, called mapM or traverse. I’m going to call
the general concept traverse from now on to make it clear that is different from map.

Map vs. Traverse

Understanding the difference between map and traverse can be hard, so let’s see if we can explain it in pictures.

First, let’s introduce some visual notation using the analogy of an “elevated” world sitting above a “normal” world.

Some of these elevated worlds (in fact almost all of them!) have apply and return functions. We’ll call these “Applicative worlds”. Examples
include Option, Result, Async, etc.

And some of these elevated worlds have a traverse function. We’ll call these “Traversable worlds”, and we’ll use List as a classic example.

If a Traversable world is on top, that produces a type such as List<a>, and
if an Applicative world is on top, that produces a type such as Result<a>.

Understanding traverse and sequence - 图3

IMPORTANT: I will be using the syntax List<_> to represent “List world” for consistency with Result<_>, etc. This is not meant to be the same as the .NET List class!
In F#, this would be implemented by the immutable list type
.

But from now on we are going to be dealing with both kinds of elevated worlds in the same “stack”.

The Traversable world can be stacked on top of the Applicative world, which produces a type such as List<Result<a>>, or alternatively,
the Applicative world world can be stacked on top of the Traversable world, which produces a type such as Result<List<a>>.

Understanding traverse and sequence - 图4

Now let’s see what the different kinds of functions look like using this notation.

Let’s start with a plain cross-world function such as a -> Result<b>, where the target world is an applicative world.
In the diagram, the input is a normal world (on the left), and the output (on the right) is an applicative world stacked on top of the normal world.

Understanding traverse and sequence - 图5

Now if we have a list of normal a values, and then we use map to transform each a value using a function like a -> Result<b>,
the result will also be a list, but where the contents are Result<b> values instead of a values.

Understanding traverse and sequence - 图6

When it comes to traverse the effect is quite different.
If we use traverse to transform a list of a values using that function,
the output will be a Result, not a list. And the contents of the Result will be a List<b>.

Understanding traverse and sequence - 图7

In other words, with traverse, the List stays attached to the normal world, and the Applicative world (such as Result) is added at the top.

Ok, I know this all sounds very abstract, but it is actually a very useful technique. We’ll see an example of this is used in practice below.

Applicative vs. monadic versions of traverse

It turns out that traverse can be implemented in an applicative style or a monadic style, so there are often two separate implementations to choose from.
The applicative versions tend to end in A and the monadic versions end in M, which is helpful!

Let’s see how this works with our trusty Result type.

First, we’ll implement traverseResult using both applicative and monadic approaches.

  1. module List =
  2. /// Map a Result producing function over a list to get a new Result
  3. /// using applicative style
  4. /// ('a -> Result<'b>) -> 'a list -> Result<'b list>
  5. let rec traverseResultA f list =
  6. // define the applicative functions
  7. let (<*>) = Result.apply
  8. let retn = Result.Success
  9. // define a "cons" function
  10. let cons head tail = head :: tail
  11. // loop through the list
  12. match list with
  13. | [] ->
  14. // if empty, lift [] to a Result
  15. retn []
  16. | head::tail ->
  17. // otherwise lift the head to a Result using f
  18. // and cons it with the lifted version of the remaining list
  19. retn cons <*> (f head) <*> (traverseResultA f tail)
  20. /// Map a Result producing function over a list to get a new Result
  21. /// using monadic style
  22. /// ('a -> Result<'b>) -> 'a list -> Result<'b list>
  23. let rec traverseResultM f list =
  24. // define the monadic functions
  25. let (>>=) x f = Result.bind f x
  26. let retn = Result.Success
  27. // define a "cons" function
  28. let cons head tail = head :: tail
  29. // loop through the list
  30. match list with
  31. | [] ->
  32. // if empty, lift [] to a Result
  33. retn []
  34. | head::tail ->
  35. // otherwise lift the head to a Result using f
  36. // then lift the tail to a Result using traverse
  37. // then cons the head and tail and return it
  38. f head >>= (fun h ->
  39. traverseResultM f tail >>= (fun t ->
  40. retn (cons h t) ))

The applicative version is the same implementation that we used earlier.

The monadic version applies the function f to the first element and then passes it to bind.
As always with monadic style, if the result is bad the rest of the list will be skipped.

On the other hand, if the result is good, the next element in the list is processed, and so on. Then the results are cons’ed back together again.

NOTE: These implementations are for demonstration only! Neither of these implementations are tail-recursive, and so they will fail on large lists!

Alright, let’s test the two functions and see how they differ. First we need our parseInt function:

  1. /// parse an int and return a Result
  2. /// string -> Result<int>
  3. let parseInt str =
  4. match (System.Int32.TryParse str) with
  5. | true,i -> Result.Success i
  6. | false,_ -> Result.Failure [str + " is not an int"]

Now if we pass in a list of good values (all parsable), the result for both implementations is the same.

  1. // pass in strings wrapped in a List
  2. // (applicative version)
  3. let goodA = ["1"; "2"; "3"] |> List.traverseResultA parseInt
  4. // get back a Result containing a list of ints
  5. // Success [1; 2; 3]
  6. // pass in strings wrapped in a List
  7. // (monadic version)
  8. let goodM = ["1"; "2"; "3"] |> List.traverseResultM parseInt
  9. // get back a Result containing a list of ints
  10. // Success [1; 2; 3]

But if we pass in a list with some bad values, the results differ.

  1. // pass in strings wrapped in a List
  2. // (applicative version)
  3. let badA = ["1"; "x"; "y"] |> List.traverseResultA parseInt
  4. // get back a Result containing a list of ints
  5. // Failure ["x is not an int"; "y is not an int"]
  6. // pass in strings wrapped in a List
  7. // (monadic version)
  8. let badM = ["1"; "x"; "y"] |> List.traverseResultM parseInt
  9. // get back a Result containing a list of ints
  10. // Failure ["x is not an int"]

The applicative version returns all the errors, while the monadic version returns only the first error.

Implementing traverse using fold

I mentioned above that the “from-scratch” implementation was not tail recursive and would fail for large lists.
That could be fixed of course, at the price of making the code more complicated.

On the other hand, if your collection type has a “right fold” function, as List does, then you can use that to make the implementation simpler, faster, and safer too.

In fact, I always like to use fold and its ilk wherever possible so that I never have to worry about getting tail-recursion right!

So, here are the re-implementations of traverseResult, using List.foldBack. I have kept the code as similar as possible,
but delegated the looping over the list to the fold function, rather than creating a recursive function.

  1. /// Map a Result producing function over a list to get a new Result
  2. /// using applicative style
  3. /// ('a -> Result<'b>) -> 'a list -> Result<'b list>
  4. let traverseResultA f list =
  5. // define the applicative functions
  6. let (<*>) = Result.apply
  7. let retn = Result.Success
  8. // define a "cons" function
  9. let cons head tail = head :: tail
  10. // right fold over the list
  11. let initState = retn []
  12. let folder head tail =
  13. retn cons <*> (f head) <*> tail
  14. List.foldBack folder list initState
  15. /// Map a Result producing function over a list to get a new Result
  16. /// using monadic style
  17. /// ('a -> Result<'b>) -> 'a list -> Result<'b list>
  18. let traverseResultM f list =
  19. // define the monadic functions
  20. let (>>=) x f = Result.bind f x
  21. let retn = Result.Success
  22. // define a "cons" function
  23. let cons head tail = head :: tail
  24. // right fold over the list
  25. let initState = retn []
  26. let folder head tail =
  27. f head >>= (fun h ->
  28. tail >>= (fun t ->
  29. retn (cons h t) ))
  30. List.foldBack folder list initState

Note that this approach will not work for all collection classes. Some types do not have a right fold,
so traverse must be implemented differently.

What about types other than lists?

All these examples have used the list type as the collection type. Can we implement traverse for other types too?

Yes. For example, an Option can be considered a one-element list, and we can use the same trick.

For example, here’s an implementation of traverseResultA for Option

  1. module Option =
  2. /// Map a Result producing function over an Option to get a new Result
  3. /// ('a -> Result<'b>) -> 'a option -> Result<'b option>
  4. let traverseResultA f opt =
  5. // define the applicative functions
  6. let (<*>) = Result.apply
  7. let retn = Result.Success
  8. // loop through the option
  9. match opt with
  10. | None ->
  11. // if empty, lift None to an Result
  12. retn None
  13. | Some x ->
  14. // lift value to an Result
  15. (retn Some) <*> (f x)

Now we can wrap a string in an Option and use parseInt on it. Rather than getting a Option of Result, we invert the stack and get a Result of Option.

  1. // pass in an string wrapped in an Option
  2. let good = Some "1" |> Option.traverseResultA parseInt
  3. // get back a Result containing an Option
  4. // Success (Some 1)

If we pass in an unparsable string, we get failure:

  1. // pass in an string wrapped in an Option
  2. let bad = Some "x" |> Option.traverseResultA parseInt
  3. // get back a Result containing an Option
  4. // Failure ["x is not an int"]

If we pass in None, we get Success containing None!

  1. // pass in an string wrapped in an Option
  2. let goodNone = None |> Option.traverseResultA parseInt
  3. // get back a Result containing an Option
  4. // Success (None)

This last result might be surprising at first glance, but think of it this way, the parsing didn’t fail, so there was no Failure at all.

Traversables

Types that can implement a function like mapXXX or traverseXXX are called Traversable. For example, collection types are Traversables as well as some others.

As we saw above, in a language with type classes a Traversable type can get away with just one implementation of traverse,
but in a language without type classes a Traversable type will need one implementation per elevated type.

Also note that, unlike all the generic functions we have created before, the type being acted on (inside the collection)
must have appropriate apply and return functions in order for traverse to be implemented. That is, the inner type must be an Applicative.

The properties of a correct traverse implementation

As always, a correct implementation of traverse should have some properties that are true no matter what elevated world we are working with.

These are the “Traversable Laws”,
and a Traversable is defined as a generic data type constructor — E<T> — plus a set of
functions (traverse or traverseXXX ) that obey these laws.

The laws are similar to the previous ones. For example, the identity function should be mapped correctly, composition should be preserved, etc.


The sequence function

Common Names: sequence

Common Operators: None

What it does: Transforms a list of elevated values into an elevated value containing a list

Signature: E<a> list -> E<a list> (or variants where list is replaced with other collection types)

Description

We saw above how you can use the traverse function as a substitute for map when you have a function that generates an applicative type such as Result.

But what happens if you are just handed a List<Result> and you need to change it to a Result<List>. That is, you need to swap the order of the worlds on the stack:

Understanding traverse and sequence - 图8

This is where sequence is useful — that’s exactly what it does! The sequence function “swaps layers”.

The order of swapping is fixed:

  • The Traversable world starts higher and is swapped down.
  • The Applicative world starts lower and is swapped up.

Note that if you aleady have an implementation of traverse, then sequence can be derived from it easily.
In fact, you can think of sequence as traverse with the id function baked in.

Applicative vs Monadic versions of sequence

Just as with traverse, there can be applicative and monadic versions of sequence:

  • sequenceA for the applicative one.
  • sequenceM (or just sequence) for the monadic one.

A simple example

Let’s implement and test a sequence implementation for Result:

  1. module List =
  2. /// Transform a "list<Result>" into a "Result<list>"
  3. /// and collect the results using apply
  4. /// Result<'a> list -> Result<'a list>
  5. let sequenceResultA x = traverseResultA id x
  6. /// Transform a "list<Result>" into a "Result<list>"
  7. /// and collect the results using bind.
  8. /// Result<'a> list -> Result<'a list>
  9. let sequenceResultM x = traverseResultM id x

Ok, that was too easy! Now let’s test it, starting with the applicative version:

  1. let goodSequenceA =
  2. ["1"; "2"; "3"]
  3. |> List.map parseInt
  4. |> List.sequenceResultA
  5. // Success [1; 2; 3]
  6. let badSequenceA =
  7. ["1"; "x"; "y"]
  8. |> List.map parseInt
  9. |> List.sequenceResultA
  10. // Failure ["x is not an int"; "y is not an int"]

and then the monadic version:

  1. let goodSequenceM =
  2. ["1"; "2"; "3"]
  3. |> List.map parseInt
  4. |> List.sequenceResultM
  5. // Success [1; 2; 3]
  6. let badSequenceM =
  7. ["1"; "x"; "y"]
  8. |> List.map parseInt
  9. |> List.sequenceResultM
  10. // Failure ["x is not an int"]

As before, we get back a Result<List>, and as before the monadic version stops on the first error, while the applicative version accumulates all the errors.


“Sequence” as a recipe for ad-hoc implementations

We saw above that having type classes like Applicative means that you only need to implement traverse and sequence once. In F# and other
languages without high-kinded types you have to create an implementation for each type that you want to traverse over.

Does that mean that the concepts of traverse and sequence are irrelevant or too abstract? I don’t think so.

Instead of thinking of them as library functions, I find that it is useful to think of them as recipes — a set of instructions
that you can follow mechanically to solve a particular problem.

In many cases, the problem is unique to a context, and there is no need to create a library function — you can create a helper function as needed.

Let me demonstrate with an example. Say that you are given a list of options, where each option contains a tuple, like this:

  1. let tuples = [Some (1,2); Some (3,4); None; Some (7,8);]
  2. // List<Option<Tuple<int>>>

This data is in the form List<Option<Tuple<int>>>. And now say, that for some reason, you need to turn it into a tuple of two lists, where each list contains options,
like this:

  1. let desiredOutput = [Some 1; Some 3; None; Some 7],[Some 2; Some 4; None; Some 8]
  2. // Tuple<List<Option<int>>>

The desired result is in the form Tuple<List<Option<int>>>.

So, how would you write a function to do this? Quick!

No doubt you could come up with one, but it might require a bit of thought and testing to be sure you get it right.

On the other hand, if you recognize that this task is just transforming a stack of worlds to another stack, you can create a function mechanically, almost without thinking.

Understanding traverse and sequence - 图9

Designing the solution

To design the solution, we need to pay attention to which worlds move up and which worlds move down.

  • The tuple world needs to end up at the top, so it will have to be swapped “up”, which in turn means that it will play the role of “applicative”.
  • The option and list worlds need to be swapped “down”, which in turn means that they will both play the role of “traversable”.

In order to do this transform then, I will need two helper functions:

  • optionSequenceTuple will move an option down and a tuple up.

Understanding traverse and sequence - 图10

  • listSequenceTuple will move a list down and a tuple up.

Understanding traverse and sequence - 图11

Do these helper functions need to be in a library? No. It’s unlikely that I will need them again, and even I need them occasionally, I’d prefer to write them scratch to
avoid having to take a dependency.

On the other hand, the List.sequenceResult function implemented earlier that converts a List<Result<a>> to a Result<List<a>> is something I do use frequently,
and so that one is worth centralizing.

Implementing the solution

Once we know how the solution will look, we can start coding mechanically.

First, the tuple is playing the role of the applicative, so we need to define the apply and return functions:

  1. let tupleReturn x = (x, x)
  2. let tupleApply (f,g) (x,y) = (f x, g y)

Next, define listSequenceTuple using exactly the same right fold template as we did before, with List as the traversable and tuple as the applicative:

  1. let listSequenceTuple list =
  2. // define the applicative functions
  3. let (<*>) = tupleApply
  4. let retn = tupleReturn
  5. // define a "cons" function
  6. let cons head tail = head :: tail
  7. // right fold over the list
  8. let initState = retn []
  9. let folder head tail = retn cons <*> head <*> tail
  10. List.foldBack folder list initState

There is no thinking going on here. I’m just following the template!

We can test it immediately:

  1. [ (1,2); (3,4)] |> listSequenceTuple
  2. // Result => ([1; 3], [2; 4])

And it gives a tuple with two lists, as expected.

Similarly, define optionSequenceTuple using the same right fold template again.
This time Option is the traversable and tuple is still the applicative:

  1. let optionSequenceTuple opt =
  2. // define the applicative functions
  3. let (<*>) = tupleApply
  4. let retn = tupleReturn
  5. // right fold over the option
  6. let initState = retn None
  7. let folder x _ = (retn Some) <*> x
  8. Option.foldBack folder opt initState

We can test it too:

  1. Some (1,2) |> optionSequenceTuple
  2. // Result => (Some 1, Some 2)

And it gives a tuple with two options, as expected.

Finally, we can glue all the parts together. Again, no thinking required!

  1. let convert input =
  2. input
  3. // from List<Option<Tuple<int>>> to List<Tuple<Option<int>>>
  4. |> List.map optionSequenceTuple
  5. // from List<Tuple<Option<int>>> to Tuple<List<Option<int>>>
  6. |> listSequenceTuple

And if we use it, we get just what we wanted:

  1. let output = convert tuples
  2. // ( [Some 1; Some 3; None; Some 7], [Some 2; Some 4; None; Some 8] )
  3. output = desiredOutput |> printfn "Is output correct? %b"
  4. // Is output correct? true

Ok, this solution is more work than having one reusable function, but because it is mechanical, it only takes a few minutes to code, and is still easier than
trying to come up with your own solution!

Want more? For an example of using sequence in a real-world problem, please read this post.


Readability vs. performance

At the beginning of this post I noted our tendency as functional programmers to map first and ask questions later.

In other words, given a Result producing function like parseInt, we would start by collecting the results and only then figure out how to deal with them.
Our code would look something like this, then:

  1. ["1"; "2"; "3"]
  2. |> List.map parseInt
  3. |> List.sequenceResultM

But of course, this does involve two passes over the list, and we saw how traverse could combine the map and the sequence in one step,
making only one pass over the list, like this:

  1. ["1"; "2"; "3"]
  2. |> List.traverseResultM parseInt

So if traverse is more compact and potentially faster, why ever use sequence?

Well, sometimes you are given a certain structure and you have no choice, but in other situations I might still prefer the two-step map-sequence approach just because it
is easier to understand. The mental model for “map” then “swap” seems easier to grasp for most people than the one-step traverse.

In other words, I would always go for readability unless you can prove that performance is impacted. Many people are still learning FP,
and being overly cryptic is not helpful, in my experience.


Dude, where’s my filter?

We’ve seen that functions like map and sequence work on lists to transform them into other types, but what about filtering? How can I filter things using these methods?

The answer is — you can’t! map, and traverse and sequence are all “structure preserving”.
If you start with a list of 10 things you still have a list of 10 things afterwards, albeit somewhere else in the stack.
Or if you start with a tree with three branches, you still have a tree of three branches at the end.

In the tuple example above, the original list had four elements, and after the transformation, the two new lists in the tuple also had four elements.

If you need to change the structure of a type, you need to use something like fold. Fold allows you to build a new structure from an old one,
which means that you can use it to create a new list with some elements missing (i.e. a filter).

The various uses of fold are worthy of their own series, so I’m going to save a discussion of filtering for another time.

Summary

In this post, we learned about traverse and sequence as a way of working with lists of elevated values.

In the next post we’ll finish up by working through a practical example that uses all the techniques that have been discussed.