[erlang-questions] How to put a guard?

igwan <>
Sat Aug 11 20:38:22 CEST 2007


Hello,
> %tail recursion
> pos2(X, L) -> position(X, L, 0).
> position(X, [X|_], N) -> 1+N;
> position(X, [_|T], N) -> mypos(X, T, 1+N).
>   

Where does mypos/3 come from ?
Also, in your tail recursion code, you don't handle the case where the 
list is empty. You don't need a guard to do this.

Something like this should work

pos(List, X) ->
  pos(List, X, 1).

pos([], _, _) ->
  0;
pos([X|_], X, N) ->
  N;
pos([_|T], X, N) ->
  pos(T, X, N + 1).


igwan



More information about the erlang-questions mailing list