Julia equivalence of Haskells unfoldr

question

#1

Might be a stupid question but I know julia has the foldl and foldr functions but I cannot find the unfold versions. For example in Haskell we have the unfoldr function which produces a list based on an initial value. Does julia have an equivalent function for this? I tried searching for it but nothing useful came up.


#2

Since it that is very close to the iterator protocol, you can just do

struct UnfoldingIterator{T,F}
    init::T
    f::F
end

Base.iterate(uf::UnfoldingIterator) = uf.init, uf.init

function Base.iterate(uf::UnfoldingIterator, state)
    maybestate = uf.f(state)
    if maybestate ≡ nothing
        nothing
    else
        state = something(maybestate)
        state, state
    end
end

Base.IteratorSize(::Type{<:UnfoldingIterator}) = Base.SizeUnknown()

Base.IteratorEltype(::Type{<:UnfoldingIterator}) = Base.EltypeUnknown()

then

julia> collect(UnfoldingIterator(10, x -> x == 0 ? nothing : Some(x-1)))
11-element Array{Int64,1}:
 10
  9
  8
  7
  6
  5
  4
  3
  2
  1
  0

#3

Cool and indeed it is. Maybe it’s worth making a Functional.jl containing this. I quite like the functional programming approach. Do you know if it’s a conscious decision to not have it in base as foldl and reduce are there?


#4

I don’t really know. I can make a PR to IterTools.jl.