DEV Community

Discussion on: JS Functional Concepts: Pipe and Compose

Collapse
 
apotre profile image
Mwenedata Apotre

I just knew pipe and now I know it differs to compose by just order of function execution! Thanks

Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

Anytime 😁

Collapse
 
dmass profile image
Douglas Massolari • Edited

That's not always true, though.
In Elm, for example, pipe |> and composition >> have the same order of execution, the difference is that pipe is imediately executed while composition returns a new function:
Note: Everything after -- is a comment in Elm

add x y =
  x + y

sub y x =
  x - y

totalWithPipe =
  1
    |> add 10
    |> sub 5 -- 6

totalWithComposition =
  let
    calculateTotal =
      add 10 >> sub 5 -- returns a function
  in
  calculateTotal 1 -- 6
Enter fullscreen mode Exit fullscreen mode

Not only in Elm, but pipe in fp-ts also works this way:

import { pipe } from 'fp-ts/function'

const len = (s: string): number => s.length
const double = (n: number): number => n * 2

// without pipe
assert.strictEqual(double(len('aaa')), 6)

// with pipe
assert.strictEqual(pipe('aaa', len, double), 6)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡

That's why the post has the tag #javascript 😁, either way love the insight! I haven't coded in Elm in ages, actually a good one, absolutely love the no runtime errors 🀩

It's sad that it got relatively few support...

Thread Thread
 
dmass profile image
Douglas Massolari

Yes, but even in Javascript this concept can be different as you can see in fp-ts’ pipe.

I love coding in Elm! It is my first option when creating a Frontend.

From what I see, it seems some companies are adopting it, so, it seems it’s growing

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

I picked the mathematical explanation for function composition:

In abstract algebra, a composite function is a function formed by the composition or successive application of more than one function. To do this, the function closest to the argument is applied to the argument, and the next function is applied to the result of the previous calculation.

in which case, this will fit in the description:

compose(function3, function2, function1)(initialArg);
Enter fullscreen mode Exit fullscreen mode

The implementation details or nuances in Elm (or any other) is a different matter of discussion 😁

BTW glad to hear Elm it's getting a bit more love!

Thread Thread
 
dmass profile image
Douglas Massolari

You are right.
But the point of my comment is pipe.
This is the one that have different implementations.
I just highlighted that the affirmation β€œpipe is the same as composition but reversed” is not always true

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡

oh! understood now 😁 my bad

Some comments have been hidden by the post's author - find out more