erlang - 如何在 Elixir/Erlang 中实现高效的 to_ascii 函数
问题描述
你将如何to_ascii
在 Elixir(或 Erlang)中实现一个高效的函数?
扫描字符串的每个字符并调用String.printable?
似乎是一个非常糟糕的选择
def to_ascii(s) do
case String.printable?(s) do
true -> s
false -> _to_ascii(String.codepoints(s), "")
end
end
defp _to_ascii([], acc), do: acc
defp _to_ascii([c | rest], acc) when ?c in 32..127, do: _to_ascii(rest, acc <> c)
defp _to_ascii([_ | rest], acc), do: _to_ascii(rest, acc)
例子:
s_in = <<"hello", 150, " ", 180, "world", 160>>
s_out = "hello world" # valid ascii only i.e 32 .. 127
解决方案
使用带有关键字参数Kernel.SpecialForms.for/1
的理解::into
s = "hello привет ¡hola!"
for <<c <- s>>, c in 32..127, into: "", do: <<c>>
#⇒ "hello hola!"
s = <<"hello", 150, "world", 160>>
for <<c <- s>>, c in 32..127, into: "", do: <<c>>
#⇒ "helloworld"
推荐阅读
- sharepoint - 通过 CSOM 读取内容类型的数据
- c# - 后续 http 请求后 TempData 仍然可用吗?
- angular - 如何在 Angular 7 中处理嵌套的 HTTP 请求?
- javascript - 在 map 函数中切换条件语句
- java - File.lastmodified() 生成错误的日期和月份
- c# - 读取一个文本文件,直到一行包含一些字符串文件,然后再次继续读取下一行,直到遇到另一个字符串
- powershell - Start-AzureRmDataFactoryV2Trigger 触发器 XXX 具有意外的资源提供程序:、意外的资源类型,或两者兼有
- android - 如何在xml中隐藏另一个组件后面的布局?
- node.js - 将基本身份验证与 loopback.js 和 ldap 一起使用
- r - 折线图 ggplot - 两条线,来自同一站点/秒的数据点