Also raises type_error if Arg is not compound:
?- arg(1,foo,X). ERROR: Type error: `compound' expected, found `foo' (an atom)
An example for "backtracking yields alternative solutions"
?- arg(Position,f(a,b,c),Term). Position = 1, Term = a ; Position = 2, Term = b ; Position = 3, Term = c.
The operator to decide whether "it's the same" is unification, not "==":
?- arg(Position,f(A,B,C),X). Position = 1, A = X ; Position = 2, B = X ; Position = 3, C = X. ?- arg(Position,f(A,B,C),B). Position = 1, A = B ; Position = 2 ; Position = 3, B = C.
A bit abstrusely:
?- arg(Position,f(a,K,h(K)),K). Position = 1, K = a ; Position = 2 ; Position = 3, K = h(K).
?- set_prolog_flag(occurs_check,true), arg(Position,f(a,K,h(K)),K). Position = 1, K = a ; Position = 2 ; false.
The above also means you can search:
?- arg(Position,f(a,b,c),b). Position = 2 ; false.
Excellent!