@match string startswith endswith

Is there a @match equivalent of this?

type =   startswith(ticker,"ABC")       ? "M1" :
         startswith(ticker,"X")         ? "M2" :
         contains(ticker,"123")         ? "M3" :
         endswith(ticker,"end")         ? "M4" : missing

something like

type = @match ticker  begin
   startswith("ABC")    => "M1"
   startswith("X")      => "M2"
   contains("123")      => "M3"
   endswith("end")      => "M4"
end

If you’re using Match.jl, you can do:

 type = @match ticker  begin
    t, if startswith(t, "ABC") end   => "M1"
    t, if startswith(t, "X") end     => "M2"
    t, if contains(t, "123") end     => "M3"
    t, if endswith(t, "end") end     => "M4"
 end

Rematch.jl allows for the slightly nicer:

 type = @match ticker  begin
    t where startswith(t, "ABC")   => "M1"
    t where startswith(t, "X")     => "M2"
    t where contains(t, "123")     => "M3"
    t where endswith(t, "end")     => "M4"
 end

MLStyle.jl comes closest to the syntax in your example, though it isn’t documented super well:

 type = @match ticker  begin
    GuardBy(startswith("ABC"))   => "M1"
    GuardBy(startswith("X"))     => "M2"
    GuardBy(contains("123"))     => "M3"
    GuardBy(endswith("end"))     => "M4"
 end
1 Like

Thanks Sundara
I’ll have to check out MLStyle.jl
pitty it needs that GuardBy on every line.

MLStyle fits your use case:

test(x) = @match x begin
    Startswith{"ABC"} => "M1"
    Startswith{"X"} => "M2"
    Contains{"123"}  => "M3"
    Endswith{"end"}  => "M4"
    _ => error("no match")
end

julia> test("ABC")
"M1"

julia> test("X")
"M2"

julia> test("123")
"M3"

julia> test("as123")
"M3"

julia> test("as123end")
"M3"

julia> test("as12end")
"M4"

To use such patterns Startswtih, Contains and Endswith, you can define them as follows:

using MLStyle

@active Startswith{s::String}(x) begin
    x isa AbstractString && startswith(x, s)
end

@active Contains{s::String}(x) begin
    x isa AbstractString && contains(x, s)
end

@active Endswith{s::String}(x) begin
    x isa AbstractString && endswith(x, s)
end

FYI: MLStyle - Active Patterns.

4 Likes

thats really slick :slight_smile:

1 Like