thautwarm / MLStyle.jl

Julia functional programming infrastructures and metaprogramming facilities
https://thautwarm.github.io/MLStyle.jl/latest/
MIT License
404 stars 39 forks source link

duplicate pattern does not work #104

Closed Roger-luo closed 3 years ago

Roger-luo commented 3 years ago

it's useful to match this pattern

@match x begin
    :($D = $D) => D
    :($B = $C) => (B, C)
    _ => nothing
end

where we expect

x = :(A = B)

gives

(:A, :B)

and

x = :(A = A)

gives

:A

but currently this does not as expected, am I missing something here?

0x0f0f0f commented 3 years ago

I'm interested too in this. Trying to figure out alternatives.

0x0f0f0f commented 3 years ago
julia> f(e) = @match e begin
               :($a + $b) && if a == b end => :(2 * $a)
               :($a + $b) => e
       end
f (generic function with 3 methods)

julia> f(:(x+x))
:(2x)

julia> f(:(x+1))
:(x + 1)

Using an if guard works. Ugly, but works. If you have a pattern with the same simbols repeated many times this becomes very ugly. Does not work in @matchast.

A possible solution may be to separate syms and automatically generate guards so that :($D = $D) becomes :($D_1 = $D_2) && if D_1 == D_2 under the hood. I may be wrong but I don't think this is the correct approach though. What if I want to override equality for expressions in my package?

Roger-luo commented 3 years ago

@0x0f0f0f actually you can do

@match ex begin
 :($A + $(&A)) => ...
end

I forget to close this.

0x0f0f0f commented 3 years ago

@Roger-luo Can you do this in matchast too?

Roger-luo commented 3 years ago

I haven't tried, but I assume yes.