Skip to content

Instantly share code, notes, and snippets.

@Warry Warry/
Last active Aug 9, 2016

What would you like to do?
Why do you use `(flip andThen)`?

Why do you use (flip andThen)?

TLDR; To use it with the pipe (|>) operator.

The actual andThen problem

Here is the signature for Task.andThen:

import Task exposing (andThen)
andThen : Task x a -> (a -> Task x b) -> Task x b

Now, imagine two (or more) tasks, where the second needs the result of the first one to proceed:

taskOfA : Task x a
taskOfB : a -> Task x b

The official way to compose them is using andThen as an operator (using backticks `):

doAthenB : Task x b
doAthenB =
 taskOfA `andThen` (\a ->
    taskOfB a

-- Equivalent to:
doAthenB =
  taskOfA `andThen` taskOfB

-- Equivalent to:
doAthenB =
  andThen taskOfA taskOfB

But, we prefer to use the pipe operator because:

  • Most elm functions take a function to call, then the data ( : (a -> b) -> List a -> List b)
  • The pipe operator works great those functions
  • It's arguably more readable and saves you some parentheses

For context, the signatures for the pipe operator, and flip:

-- Imported from Basics by default
(|>) : a -> (a -> b) -> b
flip : (a -> b -> c) -> b -> a -> c

And when we want to use pipe, there is a problem in the order of the andThen function:

doAthenB =
  taskOfA |> (\a -> andThen taskOfB a)

So we use flip, which flips the first and second parameters of the given function:

doAthenB =
  taskOfA |> (flip andThen) taskOfB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.