Skip to content

unfold API seems less than ideal #298

Closed
@matklad

Description

@matklad

Hi! recently, I've been using unfold a couple of times, and looks like it's rather tricky, at least in comparison with Kotlin's generateSequece.

I see two problems with current unfold API:

  • There's two ways to maintain state: you can use the initial_state, or you can just close over some env (I think these are equivalent in power).

  • There'a common case when the state and the Item of the iterator are the same. In this situation, you need to be careful to update the state, but return a previous value.

It seems to me that, instead of unfold, ideally there should be a couple of function:

  • repeat_call, for explicitly closing over some state and handling updates.

  • generate<T>(first: Option<T>, step: impl FnMut(&T) -> Option<T>) -> impl Iterator<Item=T> for the common case.

Here's an example usage, which compares unfold and generate:

https://github.com/matklad/libsyntax2/blob/557feed21ab4f1a6473b5f79e6ef250cf1219857/crates/libeditor/src/code_actions.rs#L42-L53

The second one looks much clearer to me :)

Or am missing some property of generate, which makes it more powerful than repeat_call or easier to use than generate?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions