Pattern
Macros
match!(exp, pat)
Matches exp against the given pattern pat. Raises
Pattern::MatchFailedError if matching fails.
a, b, c, d = nil, nil, nil, nil
Pattern.match!([1, [2, 3], 4], {a, {b, __splat(c)}, d})
values = {a, b, c, d} # => {1, 2, [3], 4}
typeof(values) # => Tuple(Array(Int32) | Int32, Int32, Array(Int32), Array(Int32) | Int32)
Pattern.match!([1, 2], {a, b, c}) # Pattern::MatchFailedError: matching against {a, b, c} failed
The code below shall be equivalent to above:
[1, [2, 3], 4] ~> {a, {b, *c}, d}
values = {a, b, c, d} # => {1, 2, [3], 4}
typeof(values) # => Tuple(Array(Int32) | Int32, Int32, Array(Int32), Array(Int32) | Int32)
[1, 2] ~> {a, b, c} # Pattern::MatchFailedError
matches?(exp, pat)
Attempts to match exp against the given pattern pat. Returns true if
matching succeeds, false if matching fails.
Due to language limitations, using this macro in a condition does not fully
constrain the types of the bound variables in the pattern; use
Pattern.try_match instead.
a, b, c, d = nil, nil, nil, nil
if Pattern.matches?([1, [2, 3], 4], {a, {b, __splat(c)}, d})
values = {a, b, c, d} # => {1, 2, [3], 4}
typeof(values) # => Tuple(Array(Int32) | Int32 | Nil, Int32 | Nil, Array(Int32) | Nil, Array(Int32) | Int32 | Nil)
end
The code below shall be equivalent to above:
if [1, [2, 3], 4] ~>? {a, {b, *c}, d}
values = {a, b, c, d} # => {1, 2, [3], 4}
typeof(values) # => Tuple(Array(Int32) | Int32, Int32, Array(Int32), Array(Int32) | Int32)
else
values = {a, b, c, d} # => {nil, nil, nil, nil}
typeof(values) # => Tuple(Nil, Nil, Nil, Nil)
end
try_match(exp, pat, &block)
Attempts to match exp against the given pattern pat. Invokes the block
body if matching succeeds. Returns nil.
This method is for testing purposes only. Language support for pattern matching should implement proper flow typing for successful matches.
a, b, c, d = nil, nil, nil, nil
Pattern.try_match([1, [2, 3], 4], {a, {b, __splat(c)}, d}) do
values = {a, b, c, d} # => {1, 2, [3], 4}
typeof(values) # => Tuple(Array(Int32) | Int32, Int32, Array(Int32), Array(Int32) | Int32)
end