I need find element position in list (as the built-in predicate nth, but here the first element has index 1). But, I need also have an output like ‘Element is not present’ if not.
I try a solution not so elegant, assigning a big value to counter.
But it’s not the correct solution!!!
I’m afraid it’s very easy but I can’t find another solution !!!
Can anyone helps me?
search(L):-
write('searching for: '),read(E),find(L,E,Pos),
out(L,E,Pos),!.
out(E,Pos):-
Pos < 10000,
write('element '),write(E),write(' is in position n. '),write(Pos),!.
out(E,Pos):-
Pos > 10000,
write('Element '),write(E),write(' is not present!'),!.
find([X|Xs],E,Pos):-
X \= E,
find(Xs,E,Pos1),
Pos is Pos1 + 1.
find([],_,10000).
find([X],X,1).
find([X|_],X,Pos):-
Pos is 1,!.
What you want is more something like this:
That way you don’t need a strange find clause that always succeeds with a large number. Just let it fail.