# Map Function to Slice with Index Names

**URL:** <https://discourse.julialang.org/t/map-function-to-slice-with-index-names/114280>\
**Category:** General Usage\
**Tags:** question\
**Created:** [May 15, 2024, 5:36am UTC](https://discourse.julialang.org/t/map-function-to-slice-with-index-names/114280 "2024-05-15T05:36:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lincoln\_Hannah](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lincoln_hannah/32/19198_2.png) [@Lincoln\_Hannah](https://discourse.julialang.org/u/Lincoln_Hannah)\
**Post date:** [May 15, 2024, 5:36am UTC](https://discourse.julialang.org/t/map-function-to-slice-with-index-names/114280/1 "2024-05-15T05:36:52Z")

</div>

I’d like to apply a function to slices of a named array such that the function has access to the array index names as well as the slice contents.  
The syntax below uses a KeyedArray and passes a NamedTuple `( slice, index1, index2 ...)` to the function. This is one possible syntax.  
Maybe one of the other named array packages already supports this ?

```julia
function my_func( (; slice, I, X ) )

    "$I $X $(slice(:a))"

end

K = KeyedArray( [1;2;;3;4;;;5;6;;7;8], A=[:a,:b], I=[:i,:j], X=[:x,:y] )

# proposed syntax
mapslices( my_func, K; dims=(:A) )

#would give the same result as 
@tullio Z[i,x] := my_func( (; slice=K[:,i,x], I=K.I[i], X=K.X[x]) )
KeyedArray( Z, I=K.I, X=K.X)

```

I’ve also put this as an AxisKeys request

> <https://github.com/mcabbott/AxisKeys.jl/issues/158>
>
> Ability to map a function to slices of a KeyedArray including the dimension inde…x names of each slice. 
> Proposed syntax below passes the slice and index names as a named tuple.
> 
> \`\`\`
> function my\_func( (; slice, I, X ) )
> 
> "$I $X $(slice(:a))"
> 
> end
> 
> K = KeyedArray( \[1;2;;3;4;;;5;6;;7;8\], A=\[:a,:b\], I=\[:i,:j\], X=\[:x,:y\] )
> 
> 
> 
> \# proposed syntax
> mapslices( my\_func, K; dims=(:A) )
> 
> \#would give the same result as 
> @tullio Z\[i,x\] := my\_func( (; slice=K\[:,i,x\], I=K.I\[i\], X=K.X\[x\]) )
> KeyedArray( Z, I=K.I, X=K.X)
> \`\`\`
