Laziness in Rust

I was just reading this article by @nikomatsakis. At some point he remarks:

This got me thinking: would it be possible to "abuse" Futures to implement laziness akin to what Haskell has i.e. to get opt-in laziness at the expression level?
There's a tiny little voice inside my head that says it might actually be possible, but I haven't played around enough with async / .await yet to know for sure.

Does anyone here have any ideas about that?

A common pattern is to use a closure as an FnOnce for this. Why would you not?


The only reason I can think of is if I wanted an async computation that I might want to have pause and resume (potentially multiple times). Why I would want that, I don't know... yet.

It's just that Niko's words made me think about the link between async and laziness.

You could accomplish that with a Stream. If you drop it part-way through (instead of continuing to poll), it won't do any further work.

1 Like

In other contexts, iterators can also be used effectively, even their unused warning message says literally that they are "lazy". For example, there's std::iter::repeat() that yields an unbounded number of copies of a value.