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

any need for unfoldr along with iterated? #133

Open
wherrera10 opened this issue May 31, 2021 · 0 comments
Open

any need for unfoldr along with iterated? #133

wherrera10 opened this issue May 31, 2021 · 0 comments

Comments

@wherrera10
Copy link

iterated(f, v) 

is almost the same as unfoldr in e.g. Haskell, except that it has no provision for ending the list by the function sending a flag value such as a Nothing. Is that correct?

Anyway, by adding Nothing handling we can get a Haskell style unfoldr:

using Lazy
"""
    unfoldr(f, seed)

Return a list created by applying f to each previous element of the list, starting
with `seed`. As in Haskell, `unfoldr` is a dual to `foldr`: while `foldr` reduces
a list to a summary value, `unfoldr` builds a list from a seed value. The function
`f` should take the element and return `nothing` if it is done producing the list,
or else return the next list element (which is also used as next function argument).

Examples:
unfoldr(x -> 3x, 2)                         # List: (2 6 18 54 162 486 1458 4374 13122 39366 118098 …)
unfoldr(n -> n <= 0 ? nothing : n - 1, 7)   # List: (7 6 5 4 3 2 1 0)
unfoldr(n -> n <= 0 ? nothing : n - 1, 700) # List: (700 699 698 697 696 695 694 693 692 691 690 …)
"""
unfoldr(f, seed) = takewhile(n -> !(n isa Nothing), iterated(x -> x isa Nothing ? nothing : f(x), seed))

Is this worth a PR, or is iterated() enough?

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

No branches or pull requests

1 participant