Dago
Dago

Reputation: 808

Prolog- How to assign an expression to variable

Hello i am trying to build an predicate which for given parameters return a whole new expression. Let say i want to create new expression by adding both numbers. So when I execute sth like this.

my_predicate(1,2,X).

Prolog would return:

X = 1+2

Unfortunately i dont know how can I build such a structure and assign it to X variable. I would be grateful for advice on this topic.

Upvotes: 3

Views: 3772

Answers (1)

tas
tas

Reputation: 8140

The predicate should describe a relation between potential arguments and expressions they could form, so why not call it args_expr/3. Here's an example for addition and multiplication. You can easily expand this approach for other expressions:

args_expr(Arg1,Arg2,Arg1 + Arg2).
args_expr(Arg1,Arg2,Arg1 * Arg2).

Example queries:

   ?- args_expr(1,2,X).
X = 1+2 ? ;
X = 1*2

   ?- args_expr((1+2),(3*4),X).
X = 1+2+3*4 ? ;
X = (1+2)*(3*4)

   ?- args_expr(1+2,3*4,X).
X = 1+2+3*4 ? ;
X = (1+2)*(3*4)

Upvotes: 5

Related Questions