Search code examples
listprologappendturbo-prolog

How to append 1 element in nested list in Prolog?


I want to append one list element in nested list:

predicates  
  append(li,li,li).

clauses 
 append([X|Y],Z,[X|W]):- append(Y,Z,W).
 append([],X,X).  

For example:

append([ [1],[2],[3] ],[4],A)
Solution: A = [ [1],[2],[3],[4] ]

Turbo Prolog said: Type Error.

How can I do this?


Solution

  • The problem is that you are defining the domains wrong, and that you are also appending two different domains (a list of list of integers with a list of integers).

    If what you want is to append lists of lists of integers (as it seems from your example) the code should be

    domains
    li = integer*
    lili = li*
    
    predicates
      append(lili, lili, lili).
    
    clauses
    append([X|Y],Z,[X|W]):- append(Y,Z,W).
    append([],X,X).
    

    and then in the example the second list should be a list of a lists two, yielding:

    append([ [1],[2],[3] ],[[4]],A).
    Solution: A = [ [1],[2],[3],[4] ]
    

    Note that the second list is [[4]] instead of [4].