MLStyle.jl icon indicating copy to clipboard operation
MLStyle.jl copied to clipboard

Defining methods via pattern matching

Open adkabo opened this issue 2 years ago • 2 comments

I often want to make a function whose entire body is a match expression. This could be interpreted as dispatch like https://github.com/MasonProtter/PatternDispatch.jl and https://github.com/jolin-io/WhereTraits.jl. Do you think it would be good to have this in MLStyle.jl?

Verbose:

eq(x,y) = @match (x,y) begin
(Some(x), Some(y)) => if x == y Some(x) else nothing end
(_, _) => nothing
end

Shorter:

@function eq(x,y) begin
(Some(x), Some(y)) => if x == y Some(x) else nothing end
(_, _) => nothing
end

Even shorter:

@function eq begin
(Some(x), Some(y)) => if x == y Some(x) else nothing end
(_,_) => nothing
end

adkabo avatar Apr 13 '22 21:04 adkabo

I think is similar to what you want: https://thautwarm.github.io/MLStyle.jl/latest/syntax/pattern-function.html

It does not have an easier-to-type shortcut if you do not use julia REPL or julia editor plugins.

thautwarm avatar Apr 14 '22 12:04 thautwarm

Note that accepts only one argument.

thautwarm avatar Apr 14 '22 12:04 thautwarm