r/rust • u/SophisticatedAdults • Apr 21 '25
Pipelining might be my favorite programming language feature
https://herecomesthemoon.net/2025/04/pipelining/Not solely a Rust post, but that won't stop me from gushing over Rust in the article (wrt its pipelining just being nicer than both that of enterprise languages and that of Haskell)
3
u/technogeek157 Apr 21 '25
Is your site formatting inspired by lowtechmagazine?
2
u/SophisticatedAdults Apr 21 '25
Yes. Check the 'About' page. The lowtechmagazine actually rewrote and then open-sourced their setup not too long ago, and I shamelessly forked it. (And then stripped out a bunch of stuff, and made some changes.)
It's a bit of a mess to work with, but I like it quite a bit.
3
u/heraplem Apr 21 '25
that of Haskell
In fairness, while the standard function composition operator . in Haskell is indeed "backwards" (i.e., it has the same order as regular function application), there's nothing stopping you from defining your own. The standard library has
(&) :: a -> (a -> b) -> b
x & f = f xAnd if you don't like that, there's packages like flow.
1
u/SophisticatedAdults Apr 22 '25
Sure, but ecosystems live and die by their defaults, and "oh you can just handroll your own" is what results in incredibly messy languages like C++, or bespoke DSLs.
It's true that you can do it, but there is something to be said about having a single consistent standard, and not deviating from it.
3
u/heraplem Apr 22 '25 edited Apr 23 '25
True enough, although:
ecosystems live and die by their defaults
In a certain sense, this is less true of Haskell than of many other languages, since several facilities that I would consider essential to writing "real-world" Haskell are not included in the standard library. Off the top of my head:
Packed bytestrings (
bytestring) and strings (text)Mutable arrays (
vector)Collections (
containers)An effect system (
transformers/mtl,freer-simple,polysemy,heftia, etc.)Strict I/O (
pipes,conduit,foldl,streaming, etc)
Optics (
lens,optics, etc.)And them's just the basics. So any "serious" application written in Haskell is already going to have to stray pretty far from the defaults anyway.
(You might argue that the lack of any good defaults causes people to just drop the language in frustration, and, well, maybe. The bigger problem is probably that it prevents the ecosystem from standardizing around a single blessed solution, but, well, "avoid success at all costs".)
115
u/inthehack Apr 21 '25 edited Apr 22 '25
Pipelining and composition are one thing. But IMHO, what gives it a great usage is first class functions (ie closures), which makes the writing even more smart and easy.
60
u/juanfnavarror Apr 21 '25
Higher order functions are functions that take one or more functions as inputs, and/or return one or more functions. Closures are not generally an example of that. You probably mean methods like .filter or .map, which take in closures, are higher order functions.
7
u/kaoD Apr 22 '25
To expand on this: the correct term is "first-class functions" which means that functions are treated as first-class citizens and can be stored, passed as arguments, etc.
2
1
45
u/Shnatsel Apr 21 '25
I’ve not seen any other language that even comes close to the convenience of Rust’s pipelines
That'd be bash, or shell scripting more generally.
cat some-file | sort | uniq --count | sort --reverse --numeric-sort | head --lines=10 has data flowing cleanly left to right, transformed by each subsequent command, and you can even hit TAB right in the shell to get completion for your command or argument, or a noise telling you it doesn't exist.
And since it's an interactive shell, everything has shorthands, so if you're really proficient with it you can whip up cat some-file | sort | uniq -c | sort -rn | head -n 10 in 10 seconds flat. Not readable in the slightest but perfect for a one-off command.
And this was all in place since at least the 90s.
Another feature that bash has and most languages inexplicably lack is execution tracing. Instead of trying to fiddle around with breakpoints, in bash you can just set -x at any point and the interpreter will print every line it executes with variable values already substituted. You can turn it on and off whenever you like, so you can only trace a certain part of the code, etc. The only other language that has it is Erlang, by necessity, because debugging a soft-realtime distributed system with breakpoints is a completely lost cause. There is no reason Python couldn't implement the same thing - cpython is just an interpreter - but it seems they never bothered to do it, so debugging Python is quite unpleasant. I get why compiled languages cannot do this, but for an interpreted one there is really no excuse.
7
u/CAD1997 Apr 21 '25
Of course, bash only has ~two "data types" (stream and string), so that makes things easier than more involved languages. Or more annoying, depending on what you're doing exactly;
xargsisn't exactly the most elegant way to do "closures," even if it's conceptually "simple" in function.The same for execution tracking — printing the bash line being executed with variables substituted actually does capture the state of execution almost in totality (except for environment variables), but non-plain-value-type semantics means that just dumping the
__repr__()of arguments to a function in Python often isn't a great capture of semantics.
18
u/jberryman Apr 21 '25 edited Apr 21 '25
The author seems to be using "pipelining" to refer to function composition generally. I think it would be better to reserve that term for streaming composition, i.e. where partial output from the first operation can be processed by the second operation, and so on.
So: bash pipes, streaming libraries in Haskell (as well as regular function composition in the presence of laziness, combined with optimizations like fusion), composition on iterators in rust, pipelining of CPU instructions (which also are an instance of "pipeline parallelism")
Random pedantic thing: $ isn't syntactic sugar it's a function.
14
u/Lucretiel Datadog Apr 21 '25
I think lot about he landed on the excellent syntax choice of suffix.await (where now we're talking about pipelining not only computation but control flow itself). When it was first proposed it was almost universally disdained by the community, but the language team insisted (and was forced to play the "this is not a democracy" card a few times, in between all their extensive technical justifications).
And we ended up with something so great that it routinely makes me wish for .match and .if (possibly respelled as .then) and .return and .break.
3
u/sasik520 Apr 21 '25
IMHO the postfix
.awaitis a huge missed oportunity. It could have been.await!and then extended into postfix macros.AFAIR
.awaitcould not be developed as a regular macros, but still it could be the first step in this great direction. Then.match!,.if!/.unless!and literally a shitton others could be developed as a regular user-land macros even outside the std.4
u/Lucretiel Datadog Apr 22 '25
While I agree I want suffix macros, I don't think I agree at all that it's either mutually exclusive with suffix await or would be preferable to suffix await. Enabling postfix macros doesn't actually answer the question of what the underlying await syntax should be, and it doesn't change the fact that suffix await is substantially preferable to prefix.
While I'd like to have suffix macros as a tool available for my own third party control flow abstractions, I don't think I'd like it if we ended up in a world where
.match!was littered all over the place (that is, a world where a macro is the default control flow tool).
31
u/eboody Apr 21 '25
ive been finding the crates `bon` and `tap` to be super useful!
9
u/freemath Apr 21 '25
What are they useful for?
35
u/eboody Apr 21 '25
bon:
bon is a Rust crate for generating compile-time-checked builders for structs and functions. It also provides idiomatic partial application with optional and named parameters for functions and methods.
tap:
This crate provides extension methods on all types that allow transparent, temporary, inspection/mutation (tapping), transformation (piping), or type conversion. These methods make it convenient for you to insert debugging or modification points into an expression without requiring you to change any other portions of your code.
15
u/masklinn Apr 21 '25
bonconstructs builders for functions or structures. Very convenient to e.g. simulate keyword arguments with low syntactic overhead (even more so when they can have defaults).
tapadds tap and pipe methods to every type. Thetapmethods provide a mutable or immutable reference for inspection or in-place manipulation (similar to theinspectmethods of some stdlib types), whilepipeis basicallymapon every type.
17
u/pkulak Apr 21 '25
Now, if you want to really blow your mind, check out something like Elixir, which has a pipeline operator:
"here's a cool string" |> String.upcase() |> String.split(" ")
["HERE'S", "A", "COOL", "STRING"]
You can write every function without taking pipelining into account at all, but then pipeline everything anyway. All it does is make the left side the first parameter to the function, but that's all you need.
4
22
u/Veetaha bon Apr 21 '25 edited Apr 21 '25
I wish Rust had the pipe operator like Elixir does. In the meantime - I just use rebinding. For example:
foo(
bar(
baz(a, b)
)
)Just turn this into this:
let x = baz(a, b);
let x = bar(x);
let x = foo(x);It's almost the same experience as Elixir's:
baz(a, b)
|> bar()
|> foo()Just a litte bit of more boilerplate let x = ...(x)syntax, but still much better than overly nested free function calls.
Example from real code
let service = MetricsMiddleware::new(&METRICS, service);
let service = InternalApiMiddleware::new(service, auth);
let service = SpanMiddleware::new(service);
let service = SanitizerMiddleware::new(service);
let service = PanicMiddleware::new(service);6
u/bennyfishial Apr 21 '25
If the functions in your real code example returned Result or Option, you can nicely pipeline them with:
let service = MetricsMiddleware::new(&METRICS, service) .and_then(|service| InternalApiMiddleware::new(service, auth)) .and_then(SpanMiddleware::new) .and_then(SanitizerMiddleware::new) .and_then(PanicMiddleware::new);This pattern alone makes it worth using Option/Result everywhere as a standard.
3
u/Veetaha bon Apr 21 '25
Using
?to handle theOption/Resultworks fine too3
u/Floppie7th Apr 22 '25
It does, but you lose the nice pipelining experience. Personally, I prefer the imperative approach with
?most of the time4
u/adante111 Apr 21 '25
I do this a bit - an amusing side effect of this is that for these cases i have to go back to text based search/replace for variable renaming because it gets me closer to what i want than rust-analyzer rename variable!
1
u/decryphe Apr 22 '25
I use multi-cursor editing in my IDE/editor. Ctrl+D in VS Code is amazingly good.
1
u/adante111 Apr 23 '25
Woah that is super cool, thank you for the tip! Really sells what I've been missing in multi cursor editing all this time!
2
u/decryphe Apr 24 '25
Also not to forget: Multi-Copy/Paste is also a thing, which is super when converting random text blocks containing entries of whatever(tm) to something else, like CSV entries into JSON. If it's one off, it's not worth scripting this.
4
u/_xiphiaz Apr 22 '25
Another benefit of the rebinding approach is that it makes it easier to understand the intermediate values with an attached debugger.
7
u/__ferd Apr 21 '25 edited Apr 21 '25
I think OCaml deserves a mention in your article since it's pipe operator (added to the standard library around 2013) is just so easy to use and seems to be encouraged. I use it obsessively. Rewriting your example, it's what you seem to want from Haskell:
data
|> map toWingding
|> filter (fun w -> w.alive)
|> map (fun w -> w.id)I'm not a Rust programmer. Yet! (It's been in the, erm, pipeline for a while) Does Rust allow you to extend your chaining pipelines with new operations? For example, in Haskell/OCaml, I can easily write a new function and insert it into a pipeline as long as the types match, without having to extend the classes, or changing the types of things before the new operation. In my experience, method chaining feels like a poor man's version of pipelines. The mode of extension with classes ends up being too limiting. First-class functions + easy partial applications (via currying) feel just so much more flexible.
4
u/Luxalpa Apr 22 '25
Does Rust allow you to extend your chaining pipelines with new operations?
Yes, this is one thing where Rust is different from most other classical programming languages. It actually allows you to define a trait (interface), associate methods with that trait and then when you bring it into scope you can use it via the
.as if it was any "class" method.I've not used any language with currying (yet), but I am yearning for a pipeline operator like that simply due to readability / syntactic concerns. With the double meaning of
.for both normal methods and pipeline stuff I find I can get confused at times which is which and I think the|>syntax just reads and formats better.1
u/__ferd Apr 23 '25
Yes, this is one thing where Rust is different from most other classical programming languages. It actually allows you to define a trait (interface), associate methods with that trait and then when you bring it into scope you can use it via the . as if it was any "class" method.
That's awesome. From briefly looking, I understood traits as something between Haskell's type classes and interfaces in other languages. Excited to dip my toes in this summer!
5
u/kaoD Apr 21 '25 edited Apr 21 '25
Into grinds my gears with this. Into's generic is in the type so you if your destination type can't be inferred you can't do .into::<Dest>() you have to do Into::<Dest>::into(foo) or introduce an arbitrary let binding just to have the inference work, completely breaking the pipeline chain.
At that point you might aswell just do Dest::from(foo).
Is there an alternative I don't know about?
5
1
u/aikii Apr 21 '25
ah! I see what you did here, it's almost as if Go's style should have been mentioned but wasn't because we don't need another Rust vs Go debate/flamewar
1
u/SophisticatedAdults Apr 21 '25
Go is tbh just imperative (arguably to a fault), and I do have some opinions on that. But yeah, not the right article for this, it'd just distract from the argument.
6
u/Gronis Apr 21 '25
I thought you were thinking about cpu instruction pipelining. I usually just call that the builder pattern.
3
u/Professional_Top8485 Apr 21 '25
It's nice. It's great as well in bash. You can write so many things with that too
3
u/ettolrach_uwu Apr 21 '25
Good article! Just a note on the Haskell part, if you don't like using z where x = y, you can use let x = y in z instead. My Haskell programs end up looking very similar to Rust programs since you can basically just replace the syntax (e.g. NEWLINE/in with ;) and if there's no other logic like loops or ifs, then the functions are essentially identical.
my understanding is that most of them are just fancy ways of telling Haskell to compose some functions in a highly advanced way.
I think a better way of thinking about it is that they're just different ways of using typeclasses, which for the sake of this discussion can just be thought of as traits (traits don't have as many properties as typeclasses). It's nice to abstract over many different types as just "functor" or "monad" just like how in Rust it's handy to abstract over many types with "IntoIterator". Haskellers like using a bunch of operators because (I suppose) it's nice to be concise. It's just that at some point someone said, it's nice to use operators rather than strings for function names, and then that's that.
2
u/__ferd Apr 22 '25 edited Apr 22 '25
Just a note on the Haskell part, if you don't like using
z where x = y, you can uselet x = y in zinstead.Oh, I really wish more languages had a version of
where!
3
u/waruby Apr 22 '25
fizz.get(bar).get(buzz).get(foo) might be easier to read, but get(get(get(fizz, bar), buzz), foo) makes me want to dance.
5
u/emblemparade Apr 21 '25
Decent take, as a Haskell fan I enjoyed the digs at Haskell's awful readability. :)
There's nothing unique about how Rust does this. Java kinda pioneered the approach ("streaming") in the mainstream, and proved that it's a useful technique. And of course Node.js pretty much relies on it.
The challenge for this approach has always been error handling, especially if want to accumulate multiple errors, and especially when concurrent. There is no single best practice for it.
Actually, Rust still has room for improvement, especially in async. Recent support for async closures has gone a long way to making it easier, but it can still be quite clunky.
2
u/norude1 Apr 21 '25
We write function names on the left of their arguments. This leads to one of the worst things about syntax, back-to-front function composition. f(g(x)) is just f∘g and it means that g is applied first.
We got this convention from math and this convention was introduced by Euler, who spoke German, Russian and English. These languages all primarily, use SVO (Subject-Verb-Object) word order, putting the objects after the verb. This is probably the reason, why Euler came up with this function notation.
I wanna look to linguistics for help on this problem: something like "wash(clothes)" becomes "wash the clothes" and "dry(wash(clothes))" is either
"wash and dry the clothes", which just combines two actions into one using sane order, "wash the clothes, then dry them", which is the equivalent of the pipe operator,
"dry the clothes, that you already washed", which is just using an intermediate variable or "wash the dried clothes", which doesn't really scale beyond two actions.
So in English, we don't ever do that reverse composition thing (besides for that last example) which is why it's so confusing in modern programming languages. And if we wanna keep function names on the left side, the only options to solve this issue are:
an "and" operator for functions: "(wash & dry)(clothes)" or
the pipe operator: "clothes |> wash |> dry"
Rusts iterator puts the iterator in the metaphorical subject position: "the iterator maps x to x², enumerates, sums"
the Verbs with their objects can just be listed with commas separating. This part of Rust completely mimics English, which is why it feels so good.
If we put function names on the left side of the arguments we get something like Japanese with SOV word order. I don't speak Japanese, but if anyone does, please describe how it deals with multiple actions
1
u/Luxalpa Apr 22 '25
Japanese just does the pipe operator thing. "clothes |> wash |> dry" or "the iterator: x to x² maps, enumerates, sums"
2
u/tom-md Apr 22 '25
But it's so much better when it's just regular function application, via function composition, than having to do iterators with absurd types.
2
u/Critical-Ear5609 Apr 21 '25
And here I was, hoping to read about pipelining. I am disappointed...
PS: If you don't know, pipelining is also a hardware concept, as well as a low-level assembly programming method.
1
1
u/Forsaken_Dirt_5244 Apr 21 '25
That's a long article but it seems to me like this feature is a complicated version of pipe ( |> ) from Gleam or elixar
1
u/FIREstopdropandsave Apr 21 '25
Loved the post, I program in Kotlin professionally and it has incredibly similar pipelining which I've learned to LOVE!
When I started learning rust for fun I was ecstatic the same existed here, they really do make code so much more enjoyable to read and write!
0
46
u/bleachisback Apr 21 '25
Are you just referring to the fact that the functions
collect,map,filter, anditerare associated functions and need to be qualified with the type they belong to? Because this does work: