0
votes

I am facing a prolog problem regarding List and Term. Then my question is how to write a predicate

transform([a,b],X)

will return X = (a,b) Or vice versa

This is weird with me because I've never faced such term before. I tried with the built in =.. but

=..((a,b,c,d),X)

returns X=[',',a,(b,c,d)] which makes me deeply disappoint. Thank you.

1
Do you want this to work for any number of elements in the list? - svick
yes it should work for any number of elements. Actually I can't understand the return X=[',',a,(b,c,d)] of =..((a,b,c,d),X). For me, it should be X=[',',a,b,c,d] - nhong
It behaves similarly as a list with a head and another list as tail. In other words, (a,b,c,d) = (a,(b,(c,d))). - svick

1 Answers

2
votes

Check something like this:

transform([A], A):-
  A=..[_].
transform([A,B], (A,B)):-
  B=..[_].
transform([A,B,C|Tail], L):-
  L=..[',',A,T],
  transform([B,C|Tail], T).

The first clause is only needed if you want transform([Item], Item).

?- transform([a,b], X).
X = (a, b) 

?- transform([a,b,c,d,e,f], X).
X = (a, b, c, d, e, f) 

?- transform(L, (a,b,c,d,e,f,g))
L = [a, b, c, d, e, f, g] 

Note that the term you are building does have a functor, it is ','/2, and it is shown with the parenthesis you are seeing.