简体   繁体   中英

How do you define an operator in prolog to make a list?

I want to define an operator "++>" in a way so that typing "a ++> b" will make a list of [a,b].

I've written the following code, but it doesn't appear to do the job.

++>(X,Y) :-
 [X,Y].

:- op(500,xfy,++>).

Does this work for you:

++>((X,Y),Z) :-Z= [X,Y].

:- op(500,xfy,++>).

[a,b,c] is just syntactic sugar for '.'(a,'.'(b,'.'(c)))) . So you may define your operator just the same and write a conversion predicate:

:- op(500,xfy,'++>').

convert('++>'(A,B),[A|R]) :-
    convert(B,R).
convert(Any,[Any]).

Example:

| ?- X = 1++>2++>3, convert(X,Y).                                    
X = 1++>2++>3
Y = [1,2,3] ?
yes
:- op(500,xfy,++>).
++>(X,Y,[X,Y]).

And use it like

?- ++>(1,2,X).
X = [1, 2].

Actually, Prolog is not oriented calculations, so operators is just synonyms to the terms. You want a term\\3, where one element is list of two another. So, you can't use 2-placed operator in that case. Btw, you can't use is in this situation, because it used only in arithmetic cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM