Skip to content

Commit bb8f826

Browse files
committed
stack(f, iter)
1 parent c6aeed6 commit bb8f826

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

base/abstractarray.jl

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2562,6 +2562,43 @@ true
25622562
stack(itr) = _stack_iter(IteratorSize(itr), itr)
25632563
stack(A::AbstractArray{<:AbstractArray}) = _typed_stack(mapreduce(eltype, promote_type, A), A)
25642564

2565+
"""
2566+
stack(f, args)
2567+
2568+
Apply `f` to each element of `args`, and `stack` the result.
2569+
2570+
See also [`mapslices`](@ref), [`mapreduce`](@ref).
2571+
2572+
# Examples
2573+
```jldoctest
2574+
julia> stack("julia") do c
2575+
(c, c-32)
2576+
end
2577+
2×5 Matrix{Char}:
2578+
'j' 'u' 'l' 'i' 'a'
2579+
'J' 'U' 'L' 'I' 'A'
2580+
2581+
julia> ans == mapreduce(c -> [c, c-32], hcat, "julia")
2582+
true
2583+
2584+
julia> stack(x -> x*x', eachcol([1 2; 10 20; 100 200]))
2585+
3×3×2 Array{Int64, 3}:
2586+
[:, :, 1] =
2587+
1 10 100
2588+
10 100 1000
2589+
100 1000 10000
2590+
2591+
[:, :, 2] =
2592+
4 40 400
2593+
40 400 4000
2594+
400 4000 40000
2595+
2596+
julia> ans == cat([1,10,100] * [1,10,100]', [2,20,200] * [1,20,200]'; dims=3)
2597+
true
2598+
```
2599+
"""
2600+
stack(f, itr) = stack(Iterators.map(f, itr))
2601+
25652602
function _stack_iter(::HasShape, itr)
25662603
w, val = _vstack_plus(itr)
25672604
reshape(w, axes(val)..., axes(itr)...)

test/abstractarray.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,6 +1577,10 @@ end
15771577
@test size(stack(Iterators.product(1:3, 1:4))) == (2,3,4)
15781578
@test stack([('a', 'b'), ('c', 'd')]) == ['a' 'c'; 'b' 'd']
15791579

1580+
# stack(f, iter)
1581+
@test stack(x -> [x, 2x], 3:5) == [3 4 5; 6 8 10]
1582+
@test stack(x -> x*x'/2, [1:2, 3:4]) == [0.5 1.0; 1.0 2.0;;; 4.5 6.0; 6.0 8.0]
1583+
15801584
# Mismatched sizes
15811585
@test_throws DimensionMismatch stack([1:2, 1:3])
15821586
@test_throws DimensionMismatch stack(x for x in [1:2, 1:3])

0 commit comments

Comments
 (0)