I'm looking to convert a Prolog term similar to this:
cons(a, cons(b, cons(c, cons(d, nil ))))
into a list:
[a, b, c, d]
I have a function to verify that cons(a, cons(b, cons(c, cons(d, nil ))))
is a proper list, as follows:
list(nil).
list(cons(_,X)):-
list(X).
which yields,
?- list(cons(a, cons(b, cons(c, cons(d, nil ))))).
true.
Now, when I pass a term like, list(cons(a, cons(b, cons(c, cons(d, nil ))))).
, and it's true , I want to then be able to convert it to a list. I can do all of the rest, I'm just stuck on the conversion from the term to a list.
Any assistance pointing me in the right direction would be greatly appreciated.
A simple solution would be:
list(nil, []).
list(cons(A,X), [A|L]):-
list(X,L).
Example:
?- list( cons(a, cons(b, cons(c, cons(d, nil )))), L).
L = [a, b, c, d].
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.