MikeInnes / Lazy.jl

I was gonna maintain this package, but then I got high
Other
469 stars 54 forks source link

any need for unfoldr along with iterated? #133

Open wherrera10 opened 3 years ago

wherrera10 commented 3 years ago
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?