Mapfoldr and inference on Tuple

I would like mapfoldr to infer on a Tuple. MWE:

using Test
prefix_combinations(x, y) = vec(((x, y) -> (x, y...)).(x, permutedims(y)))
@inferred prefix_combinations([1, 2], [(3, ), (4, )]) # OK
f1(D) = mapfoldr(Base.OneTo, prefix_combinations, D; init = [()])
@inferred f1((2, 3))            # FAILS

I can of course just write a recursive version that works:

mapfoldr_recursive(acc, f, op) = acc

function mapfoldr_recursive(acc, f, op, first, rest...)
    mapfoldr_recursive(op(f(first), acc), f, op, rest...)

f2(D) = mapfoldr_recursive([()], Base.OneTo, prefix_combinations, reverse(D)...)

@inferred f2((2, 3))            # OK

but I am wondering

  1. if there is a way to do this with mapfoldr somehow out of the box, or in a simpler way,

  2. if not, whether contributing this to Base would make sense as a special case, or if there is a package that does this already.

It looks like your example can be inferred with just

Iterators.reverse(xs::Tuple) = Base.reverse(xs)

I guess it makes sense because there are already other special cases:

1 Like

Thanks, made a PR:

1 Like