r/ProgrammingLanguages • u/Savings-Debt-5383 • Jan 05 '26
Iterator fusion similar to Rust's — are there other languages that really do this, and what enables it?
While trying to learn Rust, and while reading about iterators, I came across the following definition, which really caught my attention:
Iterator fusion is a compilation technique in which a chain of iterator adapters is combined into a single loop, eliminating intermediate iterators and producing code equivalent to an optimal hand-written implementation.
Digging a bit further, I learned that in Rust this means code like:
let sum: i32 = data
.iter()
.map(|x| x * 2)
.filter(|x| *x > 10)
.sum();can end up being equivalent (after optimization) to something like:
let mut sum = 0;
for x in data {
let y = x * 2;
if y > 10 {
sum += y;
}
}No temporary collections, no multiple passes — just a single tight loop.
This really stood out to me because, in the past, I tried implementing iterators in Go for a toy project. What I ended up with involved:
- temporary allocations,
- multiple loops over the data (even when one would be enough),
- and quite a bit of “voodoo” just to achieve laziness.
I’m sure my design wasn’t ideal, but I learned a lot from it.
What really surprised me here is the idea that iterator handling is largely resolved at compile time, rather than being a runtime library mechanism. That feels very different from what I’m used to, and honestly very appealing.
Coincidentally, I’m once again in the phase of designing yet another programming language (like the previous two attempts, there’s a good chance I’ll abandon it in six months 😄).
Reading that definition immediately made me think:
“If I were designing a language, I wouldn’t even know where to start to get something like this.”
So I have a few questions, mostly from a language-design and learning perspective:
Are there other languages that really offer this in the same sense?
Not just “the compiler might optimize it if you’re lucky” (looking at you, LINQ), but cases where programmers can reasonably expect and rely on this kind of transformation when writing idiomatic code.
What enables this kind of behavior?
From a language-design point of view:
- What kinds of design choices make iterator fusion possible?
- What choices make it hard or unrealistic?
This whole question really came from reading that one definition and thinking:
“Wow — this is a powerful idea, and I don’t even know where to begin implementing something like it.”
78
u/OpsikionThemed Jan 05 '26
Haskell does. The phrase you're looking for is "stream fusion", there are some papers that explain how it's done. (The one-sentence summary explaining how it's done is that if you define all the list-functions in terms of
foldrandbuild, you can cancel build/foldr pairs and produce exactly the optimized code you're talking about.)38
u/al2o3cr Jan 05 '26
Haskell has "loop fusion": https://markkarpov.com/tutorial/ghc-optimization-and-fusion#fusion
IMO the hardest thing about doing it automatically is handling side-effects. The fused version evaluates the same operations as the un-fused version, but in a different order. If those operations have observable side-effects or can do things like panic, then fusion changes the behavior of code.
42
u/latkde Jan 05 '26
Part of Rust's superpower is just about retaining enough type information for the optimizer, which in particular enables very good inlining.
When you have an expression like
myiter.map(|x| x+1)the resulting type isn'tIter<i32>orMap<i32>, but something more likeMyIterMap<Closure@xyz>. That is, there is no type erasure. The lambda doesn't just evaluate to a function pointer, but has a globally unique type so that calls can be statically resolved and inlined, the same for each iterator method. If you want type erasure, you have to manually opt-in viadynor an explicit lowercase-fn type – and whether you can get fancy loop fusion then depends on the optimizer's ability to do data flow analysis and devirtualization.Rust is not unique – C++ also supports expression templates, separate types for each lambda, and monomorphization. However, the STL predates support for lambdas.
12
u/thomas999999 Jan 05 '26
Pretty sure c++ ranges do roughly the same. I think its also implemented using templates only and didn’t require any extra compiler features? But im not 100% certain about this.
6
u/dist1ll Jan 05 '26 edited Jan 05 '26
I'm not aware of any special optimization Rust does to fuse iterators, other than what's done by LLVM. Seems like just a result of inlining to me. Just out of curiosity, where is the quoted paragraph from?
5
u/thedeemon Jan 05 '26 edited Jan 05 '26
D does this when used with LDC compiler. It's all about inlining and optimizing, nothing truly special for iterators / ranges. All the types and capabilities of ranges are tracked in types and known statically.
8
u/spencerwi Jan 05 '26
Echoing other folks that you're talking about Stream Fusion.
Java's Streams API (since Java 8) does that, although it's a library (albeit a built-in one, and the only built-in way to do "pipelined" operations over the built-in collection types):
...works the exact same way as your example.
The Javadocs actually have good information for once
13
u/kohugaly Jan 05 '26
It is just classic lazy iterators. There is no compiler magic in there.
The iterator has a
nextmethod which yields the next element. When you are fusing iterators, you are just creating new iterator that has its ownnextmethod, which uses the original iterator'snextmethod in its implementation.A
forloop is just syntactic sugar for a while loop, that repeatedly callsnextand breaks once it yields no element.The main thing that the optimization does is, it inlines the
nextmethods into each other. It can then simplify some of the logic when the compiler sees them in a single place. Mostly stuff like nested matching.To make the inlining possible, the methods need to be statically dispatched ie. the compiler needs to be able to determine at compile time which exact method is being called. Rust achieves this by having very good support for parametric polymorphism. That means when you have generic type like
struct Map<I,F>, and you use it somewhere, the compiler produces a new concrete type, with the type parameters replaced by concrete types. A pretty big part of it is that each closure needs to be its own type.3
u/phischu Effekt Jan 05 '26
Yes, Effekt does. We transform the following program:
Into the following loop in our core representation:
Which we then continue to transform to LLVM IR. This example uses generators and not iterators. It fuses because of our compilation technique of lexical effect handlers, and seamlessly works with other control effects like exceptions.
3
u/apopheniant Jan 05 '26
Julia has loop fusion in vectorized operations https://julialang.org/blog/2017/01/moredots/
2
u/BenchEmbarrassed7316 Jan 05 '26
https://godbolt.org/z/nhrEYrqo3
I once made an example of an optimizing compiler. Note the use of SIMD. You can also write several functions and compare them, for example with a loop and with an iterator. Don't forget about annotations so that the compiler doesn't remove them. However, if two functions return completely identical code - one of them will be removed. You can copy ASM to AI, it analyzes ASM quite well. I hope this is useful to you.
2
u/Coding-Kitten Jan 05 '26
From what I understand the "superpower" here is giving each function an anonymous individual ZST rather than a function pointer, such that with the lazy iterator implementation & all it becomes a matter of inlining it all into the simple loop you see.
2
u/corwin-haskell Jan 05 '26
Elixir.Stream
2
u/MatthewRose67 Jan 06 '26
Look at C# .NET LINQ, especially IEnumerable<T>
2
u/stylewarning Jan 05 '26
Lesser known: Common Lisp's SERIES.
1
u/Ronin-s_Spirit Jan 06 '26
There is an intermediate solution to that which is called "iterator zipping" - it still involves multiple function (iterator) calls but they're all done on the same step instead of going over an entire array and then going over it again for each iterator in the chain.
Good for run-time when you don't want to manually rewrite things as a single loop but you also don't have AOT compilation to inline everything into a single loop for you.
1
u/AndydeCleyre Jan 06 '26
I'm not sure if this is a fit, but I'm reminded of a Daslang blog post from October.
1
u/AndydeCleyre Jan 07 '26
Ooh, I'm now seeing Clojure transducers, and this exploration from a Factor developer.
1
u/mamcx Jan 16 '26
I have found that is easier to understand when you see it from the POV of query engines:
https://justinjaffray.com/query-engines-push-vs.-pull/
Also: Is not obvious at first, but doing this kind of transformation is probably positive for a compiler but negative for a interpreter!
1
u/fixermark Jan 05 '26
If memory serves, SML/NJ will do tail-call optimization and encourages users to implement loops as self-recursive functions. As long as you adhere to the (relatively short and easy-to-remember) rules for making a function tail-call optimizable, the compiler can be expected to just replace the self-recursive call with a simple loop.
Personally, I think it's a very acquired taste to do away with loops entirely, but it is what it is.