JuliaMath / InverseFunctions.jl

Interface for function inversion in Julia
Other
29 stars 8 forks source link

Inverse of `circshift(_, shifts)` #49

Open jariji opened 3 months ago

jariji commented 3 months ago

I think the inverse of circshift(_, shifts) is circshift(_, map(-, shifts)). Would that fit here?

oschulz commented 3 months ago

Hm, that's quite specialized - what do you think @devmotion ?

jariji commented 3 months ago

circshift is underappreciated but has many uses when you want to move around items in an array.

For example, suppose you have a list of items [a,b,c,d,e] in your list and you want to slide d up a couple places.

using Accessors, AccessorsExtra
julia> x = collect(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> @modify(x |> view(_, 2:4)) do y
           circshift(y, -2)
       end
5-element Vector{Int64}:
 1
 4
 2
 3
 5

Suppose you want to put 10,20 in the middle of a list. Rotate the list so the middle is at the end, append 10,20, rotate back.

julia> using Accessors, InverseFunctions

julia> InverseFunctions.inverse(f::Base.Fix2{typeof(circshift)}) = Base.Fix2(circshift, -f.x);

julia> x = [5,6,7,8,9];

julia> modify(x, @o circshift(_, 3)) do y
         append!(y, 10:10:20)
       end
7-element Vector{Int64}:
  5
  6
 10
 20
  7
  8
  9
oschulz commented 3 months ago

Sure, it's definitely useful. The only thing is, we don't really have circshift(_, shifts) in Julia yet (https://github.com/JuliaLang/julia/pull/24990), except with Base.Fix2(circshift, shifts). Is that a common use case? If so, I'm not against adding it.

jariji commented 3 months ago

Nice. Is there one for

slide d up a couple places

too?

oschulz commented 3 months ago

@jariji, do have have any example use cases in mind?

jariji commented 3 months ago

Those were the examples I had, but there might be better ones. I'll see what else I can come up with.

oschulz commented 3 months ago

Thanks - it's just that if we defines inverses also for functions with fixed arguments (beyond some basic math functions like we do now) then there might be a lot of functions in Base that could qualify, but most of them will not really come up in use cases for inverse. We do have setinverse now to quickly set inverses for more rare cases. So with "less obvious" functions that can be invertible with a fixed argument I'd suggest to wait for actual use cases.