【发布时间】:2023-03-19 00:27:01
【问题描述】:
# Erlang/OTP 24, Elixir 1.12.3
bmp_signature = <<66, 77>>
#=> "BM"
<<^bmp_signature, _::binary>> = <<66, 77, 30, 0>>
#=> ** (MatchError) no match of right hand side value: <<66, 77, 30, 0>>
为什么会这样?
简而言之,我想在一个循环中对位串进行模式匹配,而不是手动编写方法定义。所以不要这样:
@bmp_signature <<66, 77>>
…
def type(<<@bmp_signature, _::binary>>), do: :bmp
…
……类似这样的:
@signatures %{
"bmp" => <<66, 77>>,
…
}
def detect_type(file) do
find_value_func = fn {extension, signature} ->
case file do
<<^signature, _::binary>> -> extension
_ -> false
end
end
Enum.find_value(@signatures, find_value_func)
end
没有元编程可以解决吗?
【问题讨论】:
标签: elixir pattern-matching bitstring