Search code examples
listprologtype-conversion

Converting list to terms in Prolog


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))).*/

Solution

  • 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).