Skip to content

Commit

Permalink
add shortcuts for Elements() and Properties()
Browse files Browse the repository at this point in the history
  • Loading branch information
aplavin committed Jan 4, 2024
1 parent 4653ccc commit af39c94
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/sugar.jl
Original file line number Diff line number Diff line change
Expand Up @@ -430,11 +430,19 @@ macro accessor(ex)
end |> esc
end

# shortcuts:
const = Elements()
const = Properties()
IndexLens(::Tuple{Elements}) = Elements()
IndexLens(::Tuple{Properties}) = Properties()

_shortstring(prev, o::PropertyLens{field}) where {field} = "$prev.$field"
_shortstring(prev, o::IndexLens) ="$prev[$(join(repr.(o.indices), ", "))]"
_shortstring(prev, o::Function) = "$o($prev)"
_shortstring(prev, o::Base.Fix1) = "$(o.f)($(o.x), $prev)"
_shortstring(prev, o::Base.Fix2) = "$(o.f)($prev, $(o.x))"
_shortstring(prev, o::Elements) = "$prev[∗]"
_shortstring(prev, o::Properties) = "$prev[∗ₚ]"

function show_optic(io, optic)
opts = deopcompose(optic)
Expand All @@ -452,13 +460,15 @@ function show_optic(io, optic)
end
end

Base.show(io::IO, optic::Union{IndexLens, PropertyLens}) = show_optic(io, optic)
Base.show(io::IO, ::MIME"text/plain", optic::Union{IndexLens, PropertyLens}) = show(io, optic)
const _OpticsTypes = Union{IndexLens,PropertyLens,Elements,Properties}

Base.show(io::IO, optic::_OpticsTypes) = show_optic(io, optic)
Base.show(io::IO, ::MIME"text/plain", optic::_OpticsTypes) = show(io, optic)

# only need show(io, optic) here because Base defines show(io::IO, ::MIME"text/plain", c::ComposedFunction) = show(io, c)
Base.show(io::IO, optic::ComposedFunction{<:Any, <:Union{IndexLens, PropertyLens}}) = show_optic(io, optic)
Base.show(io::IO, optic::ComposedFunction{<:Any, <:_OpticsTypes}) = show_optic(io, optic)
# resolve method ambiguity with Base:
Base.show(io::IO, optic::ComposedFunction{typeof(!), <:Union{IndexLens, PropertyLens}}) = show_optic(io, optic)
Base.show(io::IO, optic::ComposedFunction{typeof(!), <:_OpticsTypes}) = show_optic(io, optic)

# debugging
show_composition_order(optic) = (show_composition_order(stdout, optic); println())
Expand Down

0 comments on commit af39c94

Please sign in to comment.