Search code examples
listprologfunctor

Checking functor in a list


If I have this:

?:check_dv([v(1,x),v(2,y)], X).

How can I check what is the second argument in, for example v(1,x) (in this case x)?

Once I have the head of the list: [Head | Tail], with Head = [v(1,x)], how can I check it?


Solution

  • If you know that all elements are of the form v(_,_), then you can simply use unification:

    Head = v(_, x)
    

    This succeeds iff Head is of this form, and works correctly in all directions.

    If the elements of the list are not so homogenous, you can use arg/3:

    arg(2, Head, x)
    

    Note that this only works if Head is sufficiently instantiated, and is for this reason alone already less preferable:

    ?- arg(2, v(a,x), x).
    true.
    
    ?- arg(2, Head, x).
    ERROR: arg/3: Arguments are not sufficiently instantiated