等同地,我如何为“单个”UTF8字符键入for?
在类型定义中,我可以使用泛型"any string“或"any utf8 string”
@type tile :: String.t # matches any string
@type tile :: <<_::8>> # matches any single byte但是看起来我不能匹配第一位为0
@type tile :: <<0::1, _::7>>单个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>>(例如,在使用模式匹配时,这些位模式匹配
<<14::4, _::4, 2::2, _::6, 2::2, _::6>> = "○"成功。)
但是当在类型匹配中使用时,编译器会很大地抱怨
== 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有没有办法把类型转换成这样的位模式?
发布于 2018-11-13 21:54:38
仅根据二进制文件的唯一事实执行You cannot typespec on binary patterns。即使你可以定义这样的规格,我也不相信透析器足够复杂,可以在这样的比赛中发现失败。您只需在运行时使用守卫和模式匹配来实现此类行为,例如:
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不幸的是,据我所知,没有办法在防护中使用位模式,您只能使用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)https://stackoverflow.com/questions/48153390
复制相似问题