Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unfold #464

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Add unfold #464

wants to merge 1 commit into from

Conversation

jesaerys
Copy link

Python gives us fold as functools.reduce, which allows us to collapse a sequence into a single value. The dual to fold is unfold, which generates a sequence from an initial value. This PR introduces two generator functions for unfold called unfold and unfold_. The only difference between them is that the former takes a single function while the latter takes three. One may be more convenient than the other depending on the use case.

See "unfold" in,

I've tested and documented both functions.

@groutr
Copy link
Contributor

groutr commented Oct 9, 2019

Thank you for taking the time to implement unfold. Your implementation seems to do something very similar to iterate.

@groutr
Copy link
Contributor

groutr commented Oct 9, 2019

An example of iterate

def doubles(x):
    return x * 2

from toolz import iterate
doubled = list(i for i in iterate(doubles, 1) if i <= 20)

@jesaerys
Copy link
Author

jesaerys commented Oct 9, 2019

Thanks for the feedback, @groutr. Your iterate example doesn't exactly translate, but I take your point. I guess unfolding can be achieved by composing something like takewhile with iterate:

from itertools import takewhile 
from typing import Tuple 

def double(t: Tuple[int, int]) -> Tuple[int, int]: 
    return (t[1] * 2, t[1] + 1) 

[t[0] for t in takewhile(lambda t: t[0] <= 20, iterate(double, (1, 1)))]                                   
# [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

@jesaerys
Copy link
Author

jesaerys commented Oct 9, 2019

Should I just close this, then? I understand being conservative about growing the API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants