More on LazyList vs Enum?

There are remarks comparing Batteries’ LazyList and Enum here, duplicating the module document strings, I think. I’m still puzzled about why I’d want one rather than the other. Can anyone point me to additional information on the differences, use cases, etc. for the two modules?

I’m not sure what backtracking is.

What I want to do (currently do with LazyList) is to create a sequence by repeated application of a function using from_loop. Then I process items as needed using at, take,map,iter`, etc.

Thanks-

The simplest on-demand sequences are built out of just functions: a sequence is a function that, when called, either tells you that the sequence is empty or give you the first element and the rest as a sequence (a function to be called again). In Batteries, this is done by Seq, and this is what you should use if you need nothing more than that (and its API suits you, of course).

LazyList adds memoization: if you have the same sequence value and ask for its head element twice, Seq will call the function twice which may incur some recomputation. Lazy values are memoized, so that on the second call they are not recomputed but just returned directly (but this requires some book-keeping that has some performance impact). If you are going to access the same elements several times, LazyList may be better.

Enum, on the contrary, is “more imperative”: once you access an element once, it is consumed, removed from the enum, and you cannot get it back. This in theory guarantees some nice memory property (you cannot leak memory by mistakenly keeping a reference to the head of the sequence), but in practice makes the implement messy, somewhat unreliable, and not very efficient.

3 Likes

Ah, thanks @gasche. That’s perfect. Just what I wanted to know.

I do want memoization at present, so I’ll stick with LazyList, but will keep the other two in mind for future uses.