【问题标题】:Substring index as function guard子字符串索引作为函数保护
【发布时间】:2018-05-11 07:50:56
【问题描述】:

我正在实现一个函数,我需要知道一个字符串是否包含一个子字符串作为保护。我尝试了以下方法:

myFunc(Number, String) when N rem 2 == 0, string:str(String, "pattern") == 0 - > do thing....

使用这种结构,我得到一个非法的守卫表达式,但我不知道为什么会发生这种情况

【问题讨论】:

    标签: erlang


    【解决方案1】:

    我得到一个非法的守卫表达式'

    在 erlang 中,您不能只调用守卫中的任何函数,例如字符串:str()。 Erlang 只允许在守卫中使用一组非常严格的函数调用。见8.25 Guard Sequences部分。

    但是,您可以在函数体中使用 case 语句来执行在守卫中非法的函数调用,然后检查返回值:

    -module(my).
    -compile(export_all).
    
    func(N, Str, Pattern) when N rem 2 == 0 ->
        case string:str(Str, Pattern) of
            0       -> io:format("The string '~s' does not contain the pattern '~s'.~n", 
                                 [Str, Pattern]);
            Index   -> io:format("'~s' contains the pattern '~s' at index ~w.~n", 
                                 [Str, Pattern, Index])
        end.
    

    在外壳中:

    29> c(my).                            
    my.erl:2: Warning: export_all flag enabled - all functions will be exported
    {ok,my}
    
    30> my:func(4, "HelloWorld", "cat").
    The string 'HelloWorld' does not contain the pattern 'cat'.
    ok
    
    31> my:func(4, "HelloWorld", "World").
    'HelloWorld' contains the pattern 'World' at index 6.
    ok
    

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 2015-04-02
      相关资源
      最近更新 更多