[erlang-questions] How to put a guard?

Jilani Khaldi <>
Sat Aug 11 19:17:18 CEST 2007


Hi All,
I am trying to write a function that returns the position of an element 
inside a list and the code works "partially", seen I couldn't find a way 
to obtain what I want:
position:pos1(a,[e,r,l,a,n,g]). => 4 (ok), but
position:pos1(k,[e,r,l,a,n,g]). => Error in process <0.30.0> with exit...
I want it to return 0

This is the code:
-module(position).
-export([pos1/2, pos2/2]).

% recurion
% pos1(X, []) -> 0; doesn't work
pos1(X, [X|_]) -> 1;
pos1(X, [_|T]) -> 1+position(X,T).


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

Thanks!

Jilani




More information about the erlang-questions mailing list