rew*_*ten 11 erlang elixir dialyzer
同样,我怎样才能为"单一"UTF8字符打字?
在类型定义中,我可以使用泛型"any string"或"any utf8 string"
@type tile :: String.t # matches any string
@type tile :: <<_::8>> # matches any single byte
Run Code Online (Sandbox Code Playgroud)
但似乎我无法匹配第一位为0
@type tile :: <<0::1, _::7>>
Run Code Online (Sandbox Code Playgroud)
单个UTF比特序列的情况是
@type tile :: <<0::1, _::7>> |
<<6::3, _::5, 2::2, _::6>> |
<<14::4, _::4, 2::2, _::6, 2::2, _::6>> |
<<30::5, _::3, 2::2, _::6, 2::2, _::6, 2::2, _::6>>
Run Code Online (Sandbox Code Playgroud)
(例如,当使用模式匹配时,这些位模式匹配
<<14::4, _::4, 2::2, _::6, 2::2, _::6>> = "?"
Run Code Online (Sandbox Code Playgroud)
成功.)
但是当在typespecs中使用时,编译器会抱怨很多
== Compilation error in file lib/board.ex ==
** (ArgumentError) argument error
(elixir) lib/kernel/typespec.ex:1000: Kernel.Typespec.typespec/3
(elixir) lib/kernel/typespec.ex:1127: anonymous fn/4 in Kernel.Typespec.typespec/3
(elixir) lib/enum.ex:1899: Enum."-reduce/3-lists^foldl/2-0-"/3
(elixir) lib/kernel/typespec.ex:1127: Kernel.Typespec.typespec/3
(elixir) lib/kernel/typespec.ex:828: anonymous fn/4 in Kernel.Typespec.typespec/3
(elixir) lib/enum.ex:1899: Enum."-reduce/3-lists^foldl/2-0-"/3
(elixir) lib/kernel/typespec.ex:828: Kernel.Typespec.typespec/3
(elixir) lib/kernel/typespec.ex:470: Kernel.Typespec.translate_type/3
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以将typepec类似于这样的位模式?
您不能仅根据二进制文件的唯一事实对二进制模式进行类型指定。即使您可以定义这样的规格,我也不相信 Dialyzer 足够复杂来发现此类匹配中的失败。您只需在运行时使用防护和模式匹配来实现此类行为,例如:
def unicode?(<<0::size(1), a::size(7)>>), do: true
def unicode?(<<6::3, _::5, 2::2, _::6>>), do: true
def unicode?(<<14::4, _::4, 2::2, _::6, 2::2, _::6>>), do: true
def unicode?(<<30::5, _::3, 2::2, _::6, 2::2, _::6, 2::2, _::6>>), do: true
def unicode?(str) when is_binary(str), do: false
Run Code Online (Sandbox Code Playgroud)
不幸的是,据我所知,无法在保护中使用位模式,您只能使用 匹配整个字节binary_part/3,但没有函数可以对位执行相同的操作。因此,您可以获得的最接近的结果是这样的(未经测试这是否有效甚至可以编译,但可以让您了解可能的情况):
defguardp is_valid_utf_part(code) when code in 0b10000000..0b10111111
defguard is_unicode(<<ascii>>) when ascii in 0b0000000..0b01111111
defguard is_unicode(<<first, second>>)
when first in 0b11000000..0b11011111
and is_valid_utf_part(second)
defguard is_unicode(<<first, second, third>>)
when first in 0b11100000..0b11101111
and is_valid_utf_part(second)
and is_valid_utf_part(third)
defguard is_unicode(<<first, second, third, fourth>>)
when first in 0b11110000..0b11110111
and is_valid_utf_part(second)
and is_valid_utf_part(third)
and is_valid_utf_part(fourth)
Run Code Online (Sandbox Code Playgroud)