# Type-inferable interleave two tuples

**URL:** <https://discourse.julialang.org/t/type-inferable-interleave-two-tuples/1805>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 31, 2017, 6:54pm UTC](https://discourse.julialang.org/t/type-inferable-interleave-two-tuples/1805 "2017-01-31T18:54:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [January 31, 2017, 6:54pm UTC](https://discourse.julialang.org/t/type-inferable-interleave-two-tuples/1805/1 "2017-01-31T18:54:46Z")

</div>

I am working through the 18.S096 course. In [lecture 3](https://github.com/stevengj/18S096-iap17/blob/master/lecture3/Types%20and%20Dispatch.ipynb), an exercise is

> Write a type-inferable function to… interleave the elements of two tuples

Is this an OK solution?

```julia
_il(bs,a,arest...) = (a,_il(arest,bs...)...)
_il(bs) = () # terminate when we run out of elements for one sequence
interleave(as,bs) = _il(bs,as...)

interleave((1,2,3), (4,5,6))

```

`@code_typed interleave((1,2,3), (4,5,6))` gives

```julia
LambdaInfo for interleave(::Tuple{Int64,Int64,Int64}, ::Tuple{Int64,Int64,Int64})
:(begin 
        SSAValue(4) = (Core.getfield)(as,2)::Int64
        SSAValue(5) = (Core.getfield)(as,3)::Int64
        # meta: location In[10] _il 1
        SSAValue(2) = (Core.getfield)(bs,2)::Int64
        SSAValue(3) = (Core.getfield)(bs,3)::Int64
        # meta: pop location
        return (Core.tuple)((Core.getfield)(as,1)::Int64,(Core.getfield)(bs,1)::Int64,SSAValue(4),SSAValue(2),SSAValue(5),SSAValue(3))::Tuple{Int64,Int64,Int64,Int64,Int64,Int64}
    end::Tuple{Int64,Int64,Int64,Int64,Int64,Int64})

```

but I am still learning how to read that, so I am unsure.

---

<div class="post-metadata">

**Author:** ![andyferris](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/andyferris/32/235_2.png) [@andyferris](https://discourse.julialang.org/u/andyferris)\
**Post date:** [February 1, 2017, 10:01am UTC](https://discourse.julialang.org/t/type-inferable-interleave-two-tuples/1805/2 "2017-02-01T10:01:24Z")

</div>

The output has been inferred fully, so that is good. One tip is to use `@code_warntype` which is a colored version of `@code_typed` and watch out for red.

The other thing to do when testing type stability with tuples is to fill the slots with different types like `(1, 2.0, true, "a")`. This ensures that inference understands the order that the tuples are put together. If they are all `Int64` and the compiler can infer the length is 6, then it will appear type stable even if the general case isn’t.
