From 07dfcf3f57036ac66c0a1e03a249bfbc41666c03 Mon Sep 17 00:00:00 2001 From: Alexander Plavin Date: Wed, 27 Dec 2023 04:16:33 -0500 Subject: [PATCH] reverse: not just arrays --- src/functionlenses.jl | 6 ++++-- test/test_functionlenses.jl | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/functionlenses.jl b/src/functionlenses.jl index 1f5911b7..3f21508b 100644 --- a/src/functionlenses.jl +++ b/src/functionlenses.jl @@ -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) diff --git a/test/test_functionlenses.jl b/test/test_functionlenses.jl index 97f38ee7..08d18c43 100644 --- a/test/test_functionlenses.jl +++ b/test/test_functionlenses.jl @@ -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]) @@ -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])