Skip to content

isless on VarName #142

@penelopeysm

Description

@penelopeysm

Sometimes, it's handy to be able to sort VarNames.

If you naively do sort(vns; by=repr) i.e. order them according to lexicographic order of their string representations, then you get things like x[10] coming before x[1].

I already actually wrote some code here to do this:

using AbstractPPL: IndexLens, PropertyLens, ComposedFunction
function Base.isless(::typeof(identity), ::Union{IndexLens,PropertyLens,ComposedFunction})
    return true
end
function Base.isless(::Union{IndexLens,PropertyLens,ComposedFunction}, ::typeof(identity))
    return false
end
Base.isless(opt1::IndexLens, opt2::PropertyLens) = true
Base.isless(opt1::PropertyLens, opt2::IndexLens) = false
function Base.isless(opt1::IndexLens, opt2::IndexLens)
    return isless(opt1.indices, opt2.indices)
end
function Base.isless(opt1::PropertyLens{sym1}, opt2::PropertyLens{sym2}) where {sym1,sym2}
    return isless(sym1, sym2)
end
function Base.isless(opt1::Union{IndexLens,PropertyLens}, opt2::ComposedFunction)
    if isequal(opt1, opt2.outer)
        return true
    else
        return isless(opt1, opt2.outer)
    end
end
function Base.isless(opt1::ComposedFunction, opt2::Union{IndexLens,PropertyLens})
    if isequal(opt1.outer, opt2)
        return false
    else
        return isless(opt1.outer, opt2)
    end
end
function Base.isless(opt1::ComposedFunction, opt2::ComposedFunction)
    if isequal(opt1.outer, opt2)
        return isless(opt1.inner, opt2.inner)
    else
        return isless(opt1.outer, opt2)
    end
end
function Base.isless(vn1::VarName{sym1}, vn2::VarName{sym2}) where {sym1,sym2}
    if sym1 == sym2
        return isless(AbstractPPL.getoptic(vn1), AbstractPPL.getoptic(vn2))
    else
        return isless(sym1, sym2)
    end
end

This was originally part of FlexiChains, but it's of course quite nasty piracy which is why I removed it. Its natural home would be AbstractPPL. And tests should be added, of course.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions