Skip to content

add getkeypath and haskeypath #76

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

Merged
merged 5 commits into from
Apr 2, 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
2 changes: 2 additions & 0 deletions docs/src/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ Functors.IterateWalk

```@docs
Functors.KeyPath
Functors.haskeypath
Functors.getkeypath
```
5 changes: 3 additions & 2 deletions src/Functors.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
module Functors

export @functor, @flexiblefunctor, fmap, fmapstructure, fcollect, execute, fleaves,
KeyPath, fmap_with_path, fmapstructure_with_path
export @functor, @flexiblefunctor, fmap, fmapstructure, fcollect, execute, fleaves,
fmap_with_path, fmapstructure_with_path,
KeyPath, getkeypath, haskeypath

include("functor.jl")
include("keypath.jl")
Expand Down
109 changes: 108 additions & 1 deletion src/keypath.jl
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Base: tail

KeyT = Union{Symbol, AbstractString, Integer}

"""
Expand All @@ -7,14 +9,46 @@ A type for representing a path of keys to a value in a nested structure.
Can be constructed with a sequence of keys, or by concatenating other `KeyPath`s.
Keys can be of type `Symbol`, `String`, or `Int`.

For custom types, access through symbol keys is assumed to be done with `getproperty`.
For consistency, the method `Base.propertynames` is used to get the viable property names.

For string and integer keys instead, the access is done with `getindex`.

See also [`getkeypath`](@ref), [`haskeypath`](@ref).

# Examples

```jldoctest
julia> kp = KeyPath(:b, 3)
KeyPath(:b, 3)

julia> KeyPath(:a, kp, :c, 4)
julia> KeyPath(:a, kp, :c, 4) # construct mixing keys and keypaths
KeyPath(:a, :b, 3, :c, 4)

julia> struct T
a
b
end

julia> function Base.getproperty(x::T, k::Symbol)
if k in fieldnames(T)
return getfield(x, k)
elseif k === :ab
return "ab"
else
error()
end
end;

julia> Base.propertynames(::T) = (:a, :b, :ab);

julia> x = T(3, Dict(:c => 4, :d => 5));

julia> getkeypath(x, KeyPath(:ab)) # equivalent to x.ab
"ab"

julia> getkeypath(x, KeyPath(:b, :c)) # equivalent to (x.b)[:c]
4
```
"""
struct KeyPath{T<:Tuple}
Expand All @@ -29,10 +63,14 @@ function KeyPath(keys::Union{KeyT, KeyPath}...)
return KeyPath(((ks...)...,))
end

Base.isempty(kp::KeyPath) = false
Base.isempty(kp::KeyPath{Tuple{}}) = true
Base.getindex(kp::KeyPath, i::Int) = kp.keys[i]
Base.length(kp::KeyPath) = length(kp.keys)
Base.iterate(kp::KeyPath, state=1) = iterate(kp.keys, state)
Base.:(==)(kp1::KeyPath, kp2::KeyPath) = kp1.keys == kp2.keys
Base.tail(kp::KeyPath) = KeyPath(Base.tail(kp.keys))
Base.last(kp::KeyPath) = last(kp.keys)

function Base.show(io::IO, kp::KeyPath)
compat = get(io, :compact, false)
Expand All @@ -45,3 +83,72 @@ end

keypathstr(kp::KeyPath) = join(kp.keys, ".")

_getkey(x, k::Integer) = x[k]
_getkey(x, k::Symbol) = getproperty(x, k)
_getkey(x::AbstractDict, k::Symbol) = x[k]
_getkey(x, k::AbstractString) = x[k]

_haskey(x, k::Integer) = haskey(x, k)
_haskey(x::Tuple, k::Integer) = 1 <= k <= length(x)
_haskey(x::AbstractArray, k::Integer) = 1 <= k <= length(x) # TODO: extend to generic indexing
_haskey(x, k::Symbol) = k in propertynames(x)
_haskey(x::AbstractDict, k::Symbol) = haskey(x, k)
_haskey(x, k::AbstractString) = haskey(x, k)

"""
getkeypath(x, kp::KeyPath)

Return the value in `x` at the path `kp`.

See also [`KeyPath`](@ref) and [`haskeypath`](@ref).

# Examples
```jldoctest
julia> x = Dict(:a => 3, :b => Dict(:c => 4, "d" => [5, 6, 7]))
Dict{Symbol, Any} with 2 entries:
:a => 3
:b => Dict{Any, Any}(:c=>4, "d"=>[5, 6, 7])

julia> getkeypath(x, KeyPath(:b, "d", 2))
6
```
"""
function getkeypath(x, kp::KeyPath)
if isempty(kp)
return x
else
return getkeypath(_getkey(x, first(kp)), tail(kp))
end
end

"""
haskeypath(x, kp::KeyPath)

Return `true` if `x` has a value at the path `kp`.

See also [`KeyPath`](@ref) and [`getkeypath`](@ref).

# Examples
```jldoctest
julia> x = Dict(:a => 3, :b => Dict(:c => 4, "d" => [5, 6, 7]))
Dict{Any,Any} with 2 entries:
:a => 3
:b => Dict{Any,Any}(:c=>4,"d"=>[5, 6, 7])

julia> haskeypath(x, KeyPath(:a))
true

julia> haskeypath(x, KeyPath(:b, "d", 1))
true

julia> haskeypath(x, KeyPath(:b, "d", 4))
false
"""
function haskeypath(x, kp::KeyPath)
if isempty(kp)
return true
else
k = first(kp)
return _haskey(x, k) && haskeypath(_getkey(x, k), tail(kp))
end
end
9 changes: 6 additions & 3 deletions test/basics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,13 @@ end
@functor A
a = A(1)
@test Functors.children(a) === (x = 1,)
Functors.@leaf A
children, re = Functors.functor(a)

struct B; x; end
Functors.@leaf B
b = B(1)
children, re = Functors.functor(b)
@test children == Functors.NoChildren()
@test re(children) === a
@test re(children) === b
end

@testset "IterateWalk" begin
Expand Down
53 changes: 53 additions & 0 deletions test/keypath.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,57 @@

kp0 = KeyPath()
@test (kp0...,) === ()

struct Tkp
a
b
c
end

function Base.getproperty(x::Tkp, k::Symbol)
if k in fieldnames(Tkp)
return getfield(x, k)
elseif k === :ab
return "ab"
else
error()
end
end

Base.propertynames(::Tkp) = (:a, :b, :c, :ab)

@testset "getkeypath" begin
x = Dict(:a => 3, :b => Dict(:c => 4, "d" => [5, 6, 7]))
@test getkeypath(x, KeyPath(:a)) == 3
@test getkeypath(x, KeyPath(:b, :c)) == 4
@test getkeypath(x, KeyPath(:b, "d", 2)) == 6

x = Tkp(3, Tkp(4, 5, (6, 7)), 8)
kp = KeyPath(:b, :c, 2)
@test getkeypath(x, kp) == 7

@testset "access through getproperty" begin
x = Tkp(3, Dict(:c => 4, :d => 5), 6);

@test getkeypath(x, KeyPath(:ab)) == "ab"
@test getkeypath(x, KeyPath(:b, :c)) == 4
end
end

@testset "haskeypath" begin
x = Dict(:a => 3, :b => Dict(:c => 4, "d" => [5, 6, 7]))
@test haskeypath(x, KeyPath(:a))
@test haskeypath(x, KeyPath(:b, :c))
@test haskeypath(x, KeyPath(:b, "d", 2))
@test !haskeypath(x, KeyPath(:b, "d", 4))
@test !haskeypath(x, KeyPath(:b, "e"))

@testset "access through getproperty" begin
x = Tkp(3, Dict(:c => 4, :d => 5), 6);

@test haskeypath(x, KeyPath(:ab))
@test haskeypath(x, KeyPath(:b, :c))
@test !haskeypath(x, KeyPath(:b, :e))
end
end
end