Skip to content

Commit

Permalink
Introduce Tuple.element_type and NamedTuple.element_type (#12011)
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil authored Apr 27, 2022
1 parent 5d394bc commit 8bf1ab7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
19 changes: 15 additions & 4 deletions src/named_tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ struct NamedTuple
{% begin %}
{
{% for key in T %}
{{ key.stringify }}: options[{{ key.symbolize }}].as(typeof(begin
x = uninitialized self
x[{{ key.symbolize }}]
end)),
{{ key.stringify }}: options[{{ key.symbolize }}].as(typeof(element_type({{ key }}))),
{% end %}
}
{% end %}
Expand Down Expand Up @@ -604,4 +601,18 @@ struct NamedTuple
i = 0
values[i]
end

# Returns a value with the same type as the value for the given *key* of an
# instance of `self`. *key* must be a symbol or string literal known at
# compile-time.
#
# The most common usage of this macro is to extract the appropriate element
# type in `NamedTuple`'s class methods. This macro works even if the
# corresponding element type is private.
#
# NOTE: there should never be a need to call this method outside the standard library.
private macro element_type(key)
x = uninitialized self
x[{{ key.symbolize }}]
end
end
19 changes: 15 additions & 4 deletions src/tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,7 @@ struct Tuple
{% begin %}
{
{% for i in 0...@type.size %}
args[{{ i }}].as(typeof(begin
x = uninitialized self
x[{{ i }}]
end)),
args[{{ i }}].as(typeof(element_type({{ i }}))),
{% end %}
}
{% end %}
Expand Down Expand Up @@ -618,4 +615,18 @@ struct Tuple
self[{{T.size - 1}}]
{% end %}
end

# Returns a value with the same type as the element at the given *index* of
# an instance of `self`. *index* must be an integer or range literal known at
# compile-time.
#
# The most common usage of this macro is to extract the appropriate element
# type in `Tuple`'s class methods. This macro works even if the corresponding
# element type is private.
#
# NOTE: there should never be a need to call this method outside the standard library.
private macro element_type(index)
x = uninitialized self
x[{{ index }}]
end
end

0 comments on commit 8bf1ab7

Please sign in to comment.