如何编写将术语转换为列表的谓词?

How do I write a predicate that converts terms to lists?

我必须实现谓词 next(Integer, List),它将采用表示为术语 next(int,List) 的列表,并将其转换为 List[Head|Tail] 表示。我该怎么做呢?我一直在努力,但找不到任何帮助如何做到这一点。(nil 是空列表)

ex:
next(1,nill) = [1]
next(4,next(3,next(2,next(1,nill)))) = [4,3,2,1]
next(22,next(11,next(9,next(6,next(3,next(2,next(5,nill))))))) = [22,11,9,6,3,2,5]

您似乎找到了解决方案,但没有识别出来。

如果你从 查看解决方案:

cons([], null).
cons([X|Xs], next(X, Rest)) :- cons(Xs, Rest).

如果您询问列表 [a, b, c] 是如何转换的,它给出:

| ?- cons([a, b, c], X).

X = next(a,next(b,next(c,null)))

现在你可以反过来问,给出next(a,next(b,next(c,null))):

这个词的列表是什么
| ?- cons(X, next(a,next(b,next(c,null)))).

X = [a,b,c] ? 

yes

与您的示例类似:

| ?- cons(X, next(4,next(3,next(2,next(1,null))))).

X = [4,3,2,1] ? 

yes
| ?- cons(X, next(22,next(11,next(9,next(6,next(3,next(2,next(5,null)))))))).

X = [22,11,9,6,3,2,5] ? 

yes

PS:我用了null而不是nill