fast-reflexes
fast-reflexes

Reputation: 5186

Pattern matching types in Prolog

Let's say I have a list looking like this:

List=[alpha(1,2),beta(3,4),gamma(4,1)]

Ok, so I want to make a certain pattern matching here... I know I can do:

Try=alpha(Y,Z).
    Try=alpha(1,2)
    Y=1
    Z=2

But I would like to do for example:

Try=X(Y,Z)
    X=alpha
    Y=1
    Z=2

...so that I can pass on the data to another predicate:

targetPredicate(Type,Value1,Value2):-
    Type=alpha
    ...

and then do something with it instead of having to make one help predicate for every type I might run into:

helpPredicate(Input):-
    Input=alpha(Value1, Value2),
    targetPredicateAlt(Value1, Value2).

helpPredicate(Input):-
    Input=beta(Value1, Value2),
    targetPredicateAlt(Value1, Value2).

helpPredicate(Input):-
    Input=gamma(Value1, Value2),
    targetPredicateAlt(Value1, Value2).

Is there any way to get around this or am I doomed to use a ton of help predicates?

Upvotes: 3

Views: 347

Answers (1)

gusbro
gusbro

Reputation: 22585

You can use the univ predicate =../2: Suppose you have Try=alpha(1,2), then

Try =..[Name, X, Y].

would yield Name = alpha, X = 1, Y = 2.

Upvotes: 4

Related Questions