MLStyle.jl
MLStyle.jl copied to clipboard
Defining methods via pattern matching
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
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.
Note that @λ
accepts only one argument.