Created
January 31, 2019 16:23
-
-
Save simenge/fa5101689093acdf915c0f3e72463fcf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Pat | |
macro match(&block) | |
case {{block.body.cond}} | |
{% for whens in block.body.whens %} | |
{% if whens.conds.first.is_a?(Cast) %} | |
when {{whens.conds.first.to}} | |
{{whens.conds.first.obj}} = {{block.body.cond}} | |
{{whens.body}} | |
{% elsif whens.conds.first.is_a?(ArrayLiteral) %} | |
when {{block.body.cond}}.is_a?(Array) && {{block.body.cond}}.as(Array).size == {{whens.conds.first.size}} | |
{{whens.body}} | |
{% else %} | |
when {{whens.conds.first}} | |
{{whens.body}} | |
{% end %} | |
{% end %} | |
else | |
{{block.body.else}} | |
end | |
end | |
end | |
include Pat | |
def foo(x : String|Int|Array(String|Int)) | |
match { | |
case x | |
when y.as(String) # introduces a new variable y : String | |
puts "String = #{y}" | |
when 1 | |
puts "one" | |
else | |
puts "Int = #{x}" | |
end | |
} | |
end | |
foo "a" | |
foo 1 | |
foo 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment