Converting list to terms in Prolog

浪子不回头ぞ 提交于 2020-01-16 09:13:39

问题


I have to implement the predicate cons(List, Term) that will take a list [Head|Tail] and convert it to terms, represented as next(Head, Tail). How do I do this? I don't even know where to start.

Here is the example of a successful query given in the question:

cons([a,b,c],X).  /*query returns X=next(a,next(b,next(c,null))).*/

回答1:


Doing most anything with lists will require that you consider two cases: the empty list and a list with a head and a sublist. Usually your base case is handling the empty list and your inductive case is handling the list with sublist.

First consider your base case:

cons([], null).

Now deal with your inductive case:

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


来源:https://stackoverflow.com/questions/58296847/converting-list-to-terms-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!