Skip to content

Commit

Permalink
reverse: not just arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
aplavin committed Dec 27, 2023
1 parent a10576b commit 07dfcf3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
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
4 changes: 4 additions & 0 deletions test/test_functionlenses.jl
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ 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])
Expand All @@ -178,6 +181,7 @@ end
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

0 comments on commit 07dfcf3

Please sign in to comment.