Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Elixir/Erlang中实现高效的to_ascii函数_Erlang_Elixir_Ascii - Fatal编程技术网

如何在Elixir/Erlang中实现高效的to_ascii函数

如何在Elixir/Erlang中实现高效的to_ascii函数,erlang,elixir,ascii,Erlang,Elixir,Ascii,您将如何在Elixir或Erlang中实现高效的to_ascii函数 扫描字符串的每个字符并调用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:

您将如何在Elixir或Erlang中实现高效的to_ascii函数

扫描字符串的每个字符并调用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
使用理解:

你好,你好! 对于使用理解:

你好,你好! 对于Erlang中的

1> Bin = <<"hello привет ¡hola!"/utf8>>.
<<104,101,108,108,111,32,208,191,209,128,208,184,208,178,
  208,181,209,130,32,194,161,104,111,108,97,33>>
2> << <<C>> || <<C>> <= Bin, C >= 32, C =< 127 >>. 
<<"hello  hola!">>
3> [ C || <<C>> <= Bin, C >= 32, C =< 127 ].      
"hello  hola!"
在二郎

1> Bin = <<"hello привет ¡hola!"/utf8>>.
<<104,101,108,108,111,32,208,191,209,128,208,184,208,178,
  208,181,209,130,32,194,161,104,111,108,97,33>>
2> << <<C>> || <<C>> <= Bin, C >= 32, C =< 127 >>. 
<<"hello  hola!">>
3> [ C || <<C>> <= Bin, C >= 32, C =< 127 ].      
"hello  hola!"

显然不是我;责怪何塞:显然不是我;责怪何塞: