Best practices

pairs doesn’t seem to be compatible with map the way that enumerate is… is there an OffsetArrays-compatible alternative to enumerate that is map compatible?

Can you show an example of the incompatibility?

1 Like

enumerate can be mapped over:

julia> map(enumerate(rand(10))) do (i,x)
               (i,x)
       end
10-element Vector{Tuple{Int64, Float64}}:
 (1, 0.3408824363518682)
 (2, 0.052613595813357006)

pairs can not:

julia> map(pairs(rand(10))) do (i,x)
               (i,x)
       end
ERROR: map is not defined on dictionaries

Perhaps not as straightforward, but one may define

julia> _pairs(v) = zip(eachindex(v), v)
_pairs (generic function with 1 method)

which can be mapped over:

julia> v = OffsetArray(1:4, 2);

julia> map(_pairs(v)) do x
       x
       end
4-element OffsetArray(::Vector{Tuple{Int64, Int64}}, 3:6) with eltype Tuple{Int64, Int64} with indices 3:6:
 (3, 1)
 (4, 2)
 (5, 3)
 (6, 4)

maybe this helps

 function mapover(ints)
      isodd(length(ints)) && error("input must be of even length")
      xys = Iterators.flatmap(pairs(ints)) do x
          x
      end
      ixs = collect(xys)
      twotuples = ((ixs[i], ixs[i+1]) for i=1:2:length(ixs))
      collect(twotuples)
  end

 ints = rand(1:999, 6);
 result = mapover(ints);

 ints'
 # 1×6 adjoint(::Vector{Int64}) with eltype Int64:
 #    157  11  305  977  626  989

 result
 #= 6-element Vector{Tuple{Int64, Int64}}:
 (1, 157)
 (2, 11)
 (3, 305)
 (4, 977)
 (5, 626)
 (6, 989)
=#