1
votes

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.

1
I've tried a few different things, like this for example: {create_list(cons(,X), L):- append(, L, L2), L = L2.} Is that along the lines of what you were thinking? - quiver13
I think it's just the formatting. There's an underscore in my code, but it didn't show up in the comment. - quiver13
The canonical form of a list in Prolog happens to be '.'(H, T) where H is the head and T is the tail (or rest) of the list. The bracket notation [...] is just a syntactic "sugar". So '.' is actually Prolog's version of cons since the real form of [a,b,c,d] is '.'(a, '.'(b, '.'(c, '.'(d, [])))). - lurker

1 Answers

2
votes

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].