首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为单字母ASCII字符串(值0-127)键入127?

如何为单字母ASCII字符串(值0-127)键入127?
EN

Stack Overflow用户
提问于 2018-01-08 23:33:58
回答 1查看 470关注 0票数 11

等同地,我如何为“单个”UTF8字符键入for?

在类型定义中,我可以使用泛型"any string“或"any utf8 string”

代码语言:javascript
复制
@type tile :: String.t # matches any string
@type tile :: <<_::8>> # matches any single byte

但是看起来我不能匹配第一位为0

代码语言:javascript
复制
@type tile :: <<0::1, _::7>>

单个UTF比特序列情况将是

代码语言:javascript
复制
@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>>

(例如,在使用模式匹配时,这些位模式匹配

代码语言:javascript
复制
<<14::4, _::4, 2::2, _::6, 2::2, _::6>> = "○"

成功。)

但是当在类型匹配中使用时,编译器会很大地抱怨

代码语言:javascript
复制
== 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

有没有办法把类型转换成这样的位模式?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 21:54:38

仅根据二进制文件的唯一事实执行You cannot typespec on binary patterns。即使你可以定义这样的规格,我也不相信透析器足够复杂,可以在这样的比赛中发现失败。您只需在运行时使用守卫和模式匹配来实现此类行为,例如:

代码语言:javascript
复制
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匹配整个字节,但是没有函数可以对位执行相同的操作。所以你能得到的最接近的东西是这样的(没有测试过它是否工作,甚至是编译,但给了你关于什么是可能的大体视图):

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48153390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档