Hacker News new | past | comments | ask | show | jobs | submit login

Many functional languages have |> for piping, but chained method calls are also a lot like pipelines. Data goes from left to right. This javascript expression:

  [1, 2, 3].map(n => n + 1).join(',').length
Is basically like this shell command:

  seq 3 | awk '{ print $1 + 1 }' | tr '\n' , | wc -c
(the shell version gives 6 instead of 5 because of a trailing newline, but close enough)



But each successive 'command' is a method on what's constructed so far; not an entirely different command to which we delegate processing of what we have so far.

The Python:

   length(','.join(map(lambda n: n+1, range(1, 4)))
is a bit closer, but the order's now reversed, and then jumbled by the map/lambda. (Though I suppose arguably awk does that too.)


That's true. It's far from being generally applicable. But it might be the most "mainstream" pipe-like processing notation around.

Nim has an interesting synthesis where a.f(b) is only another way to spell f(a, b), which (I think) matches the usual behavior of |> while still allowing familiar-looking method-style syntax. These are equivalent:

  [1, 2, 3].map(proc (n: int): int = n + 1).map(proc (n: int): string = $n).join(",").len
  
  len(join(map(map([1, 2, 3], proc (n: int): int = n + 1), proc (n: int): string = $n), ","))
The difference is purely cosmetic, but readability matters. It's easier to read from left to right than to have to jump around.


C# extension methods provide the same syntax, and it is used for all of its LINQ pipeline methods. It's amazing how effective syntactic sugar can be for readability.


In Julia, this would be:

1:3 |> x->x+1 |> x->join(x,",") |> length


Small correction (or it won't run on my system):

  1:3 |> x -> map(y -> y+1, x) |> x -> join(x, ",") |> length
All those anonymous functions seem a bit distracting, though https://github.com/JuliaLang/julia/pull/24990 could help with that.


Ok, in Julia 1.0+ you just have to use the dot operator:

1:3 |> x->x.+1 |> x->join(x,",") |> length

Note the dot in x.+1, that tells + to operate on each element of the array (x), and not the array itself.


Ok... not sure which version of Julia you're using, but I'm on 0.5 and it works there... Maybe it changed in a later version


Maybe a bit nicer

    (1:3 .|> x->x+1) |> x->join(x,",") |> length




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: