Skip to content

Instantly share code, notes, and snippets.

@Warry
Last active August 9, 2016 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Warry/c8674de11335f9c9d24b53a0adbbc6c5 to your computer and use it in GitHub Desktop.
Save Warry/c8674de11335f9c9d24b53a0adbbc6c5 to your computer and use it in GitHub Desktop.
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 (List.map : (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