检查字符串中的每个字符的保护程序

huangapple go评论53阅读模式
英文:

guard to check each character in the string

问题

我的函数接受一个字符串,我需要检查每个单独的字符是否为"0"或"1"。如何做到这一点?我尝试过以下方法:

defguard is_bit_string(str)
           when is_binary(str) and
                  byte_size(str) == 1 and
                  binary_part(str, 0, 1) in ["0", "1"]

defguard is_bit_string(str)
           when is_binary(str) and
                  binary_part(str, 0, 1) in ["0", "1"] and
                  is_bit_string(binary_part(str, 1, byte_size(str) - 1))

但是结果是守卫不能递归(当我得到以下错误时):

(CompileError) cannot find or invoke local is_bit_string/1 inside guards. Only macros can be invoked in guards and they must be defined before their invocation. Called as: is_bit_string(binary_part(str, 1, byte_size(str) - 1))

在函数体内检查这一点的问题是,我需要为多个函数检查这个条件,这只会导致不必要的重复。是否有其他方法,以便我不需要在每个函数内部执行这个检查?

英文:

My function takes a string and I need to check each individual character is either "0" or "1".
How to do that?
I have tried this:

  defguard is_bit_string(str)
           when is_binary(str) and
                  byte_size(str) == 1 and
                  binary_part(str, 0, 1) in ["0", "1"]

  defguard is_bit_string(str)
           # byte_size(str) == 1 and
           when is_binary(str) and
                  binary_part(str, 0, 1) in ["0", "1"] and
                  is_bit_string(binary_part(str, 1, byte_size(str) - 1))

But turns out gaurd can't be recursive(ig as i get following error:

(CompileError) cannot find or invoke local is_bit_string/1 inside guards. Only macros can be invoked in a guards and they must be defined before their invocation. Called as: is_bit_string(binary_part(str, 1, byte_size(str) - 1))

The problem with checking this inside the function body is I need to check this for multiple functions so it will just be unwanted repition. Are there other ways so that I don't need to do this inside every function?

答案1

得分: 3

我建议使用此函数替代:

def is_bit_string?(str) when is_binary(str) do
  str
  |> String.graphemes()
  |> Enum.all?(fn c -> c in ["0","1"] end)
end

def is_bit_string?(_), do: false
英文:

I will propose using this function instead:

def is_bit_string?(str) when is_binary(str) do
  str
  |> String.graphemes()
  |> Enum.all?(fn c -> c in ["0","1"] end)
end

def is_bit_string?(_), do: false

huangapple
  • 本文由 发表于 2023年7月7日 03:05:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定