When to prefer `and` over `andalso` in guard tests

前端 未结 4 841
别那么骄傲
别那么骄傲 2021-02-02 08:48

I am curious why the comma ‹,› is a shortcut for and and not andalso in guard tests.

Since I\'d call myself a “C native” I fail to see any shor

4条回答
  •  遥遥无期
    2021-02-02 09:31

    Adam Lindbergs link is right. Using the comma does generate better beam code than using andalso. I compiled the following code using the +to_asm flag:

    a(A,B) ->
        case ok of
            _ when A, B -> true;
            _ -> false
        end.
    aa(A,B) ->
        case ok of
            _ when A andalso B -> true;
            _ -> false
        end.
    

    which generates

    {function, a, 2, 2}.
      {label,1}.
        {func_info,{atom,andAndAndalso},{atom,a},2}.
      {label,2}.
        {test,is_eq_exact,{f,3},[{x,0},{atom,true}]}.
        {test,is_eq_exact,{f,3},[{x,1},{atom,true}]}.
        {move,{atom,true},{x,0}}.
        return.
      {label,3}.
        {move,{atom,false},{x,0}}.
        return.
    
    {function, aa, 2, 5}.
      {label,4}.
        {func_info,{atom,andAndAndalso},{atom,aa},2}.
      {label,5}.
        {test,is_atom,{f,7},[{x,0}]}.
        {select_val,{x,0},{f,7},{list,[{atom,true},{f,6},{atom,false},{f,9}]}}.
      {label,6}.
        {move,{x,1},{x,2}}.
        {jump,{f,8}}.
      {label,7}.
        {move,{x,0},{x,2}}.
      {label,8}.
        {test,is_eq_exact,{f,9},[{x,2},{atom,true}]}.
        {move,{atom,true},{x,0}}.
        return.
      {label,9}.
        {move,{atom,false},{x,0}}.
        return.
    

    I only looked into what is generated with the +to_core flag, but obviously there is a optimization step between to_core and to_asm.

提交回复
热议问题