Skip to content

Instantly share code, notes, and snippets.

@simenge
Created January 31, 2019 16:23
Show Gist options
  • Save simenge/fa5101689093acdf915c0f3e72463fcf to your computer and use it in GitHub Desktop.
Save simenge/fa5101689093acdf915c0f3e72463fcf to your computer and use it in GitHub Desktop.
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