Search code examples
erlangguard

Why do i get syntax error before a guard in Erlang?


I am trying to understand why i get this error in Erlang in a guard:

> d:/Intro/hello.erl:17: syntax error before: 'when'
> d:/Intro/hello.erl:13: function dispatch/1 undefined
> d:/Intro/hello.erl:2: Warning: export_all flag enabled - all functions
> will be exported error

Code

-module(hello).
-compile([export_all,debug_info]).
-export([pany/1]).


isList([])->true;
isList([_|_])->true;
isList(_)->false.

pany(X)->
    IsList=isList(X),
    Result=if IsList == true -> "Its a list";
              IsList == false -> dispatch(X)
            end,
    Result.

dispatch(T)-> when T>3 ->
    Val=if T > 4 -> 55 ;
           T >5 -> 66 ;
        end,
    if (Val+1)==67 -> "lalalal" end;
dispatch(_)->"no result".

Why does it say dispatch is undefined ? I do not want to export it , its used only internally in the module. Also is there a problem with using the result of a complex expression in a if ? I know you are not allowed to use user-defined expressions in guards , but i suppose results of expressions are ok.


Solution

  • At first, you added compile options -compile([export_all,debug_info]). so it will enable export all functions in module. Solution: remove it

    Your dispatch/1 function have some redundancy -> and ;. You should change it like below:

    -module(test).
    -compile([debug_info]).
    -export([pany/1]).
    
    
    isList([])->true;
    isList([_|_])->true;
    isList(_)->false.
    
    pany(X)->
        IsList=isList(X),
        Result=if IsList == true -> "Its a list";
                  IsList == false -> dispatch(X)
                end,
        Result.
    
    dispatch(T) when T>3 ->
        Val=if T > 4 -> 55 ;
               T >5 -> 66 
            end,
        if (Val+1)==67 -> "lalalal" end;
    dispatch(_)->"no result".