omega
omega

Reputation: 43833

How to pattern match an element in a list in prolog?

In prolog how can you pattern match an element in a list? For example, if the list was like

[1/2,1/3,2/5,3/6]

then you can do something like

one([..,1/A,..]) :- A=2.
one([..,1/A,..]) :- A=3.

Thanks.

Upvotes: 2

Views: 4355

Answers (1)

user1812457
user1812457

Reputation:

Selecting elements of a list can be done in several ways, depends what you want to do with it. For example, use select/3:

?- select(1/A, [1/2,1/3,2/5,3/6], Rest).
A = 2,
Rest = [1/3, 2/5, 3/6] ;
A = 3,
Rest = [1/2, 2/5, 3/6] ;
false.

Or using member/2:

?- member(1/A, [1/2,1/3,2/5,3/6]).
A = 2 ;
A = 3 ;
false.

You can combine select and member with predicates that collect all results of backtracking, like bagof or findall, or forall (if you need the side effects)

Or if you feel inclined, you can actually enumerate all elements, matching only the ones you need:

foo([1/A|Xs]) :- !, write(A), nl, foo(Xs).
foo([_X|Xs]) :- foo(Xs).
foo([]).

?- foo([1/2,1/3,2/5,3/6]).
2
3
true.

Although I have the feeling this last one is not very good Prolog, as it uses a cut and the predicate has a side effect. The point was to show how you can use matching and iterate through the elements of a list.

Upvotes: 2

Related Questions