[erlang-questions] illegal guard expression with lists:nth

Robert Virding <>
Thu Jun 11 11:49:28 CEST 2009


2009/6/11 Roberto Ostinelli <>

> dear all,
>
> why does the following expression give me an 'illegal guard expression' at
> compile?
>
> if
>        lists:nth(2, List) =:= "test" ->
> [...]
>
> lists:nth returns a term, thus i should be enabled to use it. on the
> contrary, the following expression is accepted:
>
> if
>        length(List) =:= 3 ->
> [...]
>
> am i missing a point?


Sort of. :-) The reason is that if only allows guard tests and while
length/1 is a valid guard tests no calls to erlang functions are. So if is
really:

if <guard test> -> ...;
   <guard test> -> ...;
   ...
end

That is why an else case is usually written as true -> ... as true is a
guard test which always succeeds.

Robert


More information about the erlang-questions mailing list