Search code examples
prolog

How to find some specific nodes/elements in a list?


I have a list in this form:

[node(2,5,4,3),node(3,5,4,3),node(2,10,12,4),node(5,2,2,2)]

I need a method that returns all the nodes that have the first value of 2. Then:

[node(2,5,4,3),node(2,10,12,4)]

I tried different methods but without success.

Thanks in advance.


Solution

  • Use this code:

    | ?- findall(
           node(2,X,Y,Z),
           member(node(2,X,Y,Z),[node(2,5,4,3),node(3,5,4,3),node(2,10,12,4),node(5,2,2,2)]),
           Nodes).
    
    Nodes = [node(2,5,4,3),node(2,10,12,4)]
    
    yes