Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow one-liner match statements #96

Merged
merged 4 commits into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "MLStyle"
uuid = "d8e11817-5142-5d16-987a-aa16d5891078"
authors = ["thautwarm <twshere@outlook.com>"]
version = "0.4.0"
version = "0.4.1"

[extras]
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Expand Down
18 changes: 17 additions & 1 deletion docs/syntax/pattern.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
Patterns
=======================

Patterns provide convenient ways to manipulate data.
Patterns provide convenient ways to manipulate data. The basic syntax for pattern matching with MLStyle is of the form
```julia
@match data begin
pattern1 => result1
pattern2 => result2
...
patternn => resultn
end
```
MLStyle will first test if `data` is matched by `pattern1` and if it does match, return `result1`. If `pattern1` does not match, then MLStyle moves on to the next pattern. If no pattern in the list matches `data`, an error is thrown.

In version 0.4.1 and newer, if you only have a single pattern you may instead write
```julia
@match data pattern => result
```
without the block syntax.


Literal Patterns
------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/MatchImpl.jl
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ end
@specialize

function gen_match(val, tbl, __source__::LineNumberNode, __module__::Module)
@assert Meta.isexpr(tbl, :block)
Meta.isexpr(tbl, :block) || (tbl = Expr(:block, tbl))
branches = Pair{Function,Tuple{LineNumberNode,Int}}[]
k = 0
ln = __source__
Expand Down
4 changes: 4 additions & 0 deletions test/match.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,8 @@
@test ast_match(:x) === nothing
end

@testset "one-liner match" begin
@test (@match 1 1 => 2) == 2
@test (@match [1, 2, 3] [hd, tl...] => (hd, tl)) == (1, [2,3])
end
end