Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reverse: support collections other than vectors #123

Merged
merged 2 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/functionlenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@ function set(x::AbstractArray, ::typeof(vec), v::AbstractVector)
res
end

# set reverse(): keep vector type, change its values
function set(x::AbstractVector, ::typeof(reverse), v::AbstractVector)
# set reverse(): keep collection type, change its values
set(::Tuple, ::typeof(reverse), v) = reverse(Tuple(v))
set(x::NamedTuple, ::typeof(reverse), v) = @set reverse(Tuple(x)) = v
function set(x::AbstractVector, ::typeof(reverse), v)
res = similar(x, eltype(v))
res .= v
reverse!(res)
Expand Down
9 changes: 9 additions & 0 deletions test/test_functionlenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ using Test
using Dates
using Unitful
using LinearAlgebra: norm, diag
using AxisKeys
using InverseFunctions: inverse
using Accessors: test_getset_laws, test_modify_law
using Accessors
Expand Down Expand Up @@ -169,10 +170,18 @@ end

B = @set reverse(vec(A)) = 1:6
@test B == [6 4 2; 5 3 1]
@test set([1, 2], reverse, (3, 4)) == [4, 3]
@test set((1, 2), reverse, [3, 4]) === (4, 3)
@test set((a=1, b=2), reverse, [3, 4]) === (a=4, b=3)

C = KeyedArray([1,2,3], x=[:a, :b, :c])
@test (@set vec(C) = [5,6,7])::KeyedArray == KeyedArray([5,6,7], x=[:a, :b, :c])
@test (@set reverse(C) = [5,6,7])::KeyedArray == KeyedArray([7,6,5], x=[:a, :b, :c])

test_getset_laws(size, A, (1, 6), (3, 2))
test_getset_laws(vec, A, 10:15, 21:26)
test_getset_laws(reverse, collect(1:6), 10:15, 21:26)
test_getset_laws(reverse, [3, 4], (1, 2), (:a, :b); cmp=(x,y) -> collect(x) == collect(y))

@test @inferred(modify(x -> x ./ sum(x), [1, -2, 3], @optic filter(>(0), _))) == [0.25, -2, 0.75]
@test isequal(modify(x -> x ./ sum(x), [1, missing, 3], skipmissing), [0.25, missing, 0.75])
Expand Down
Loading