How to append 1 element in nested list in Prolog?

2.1k Views Asked by At

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?

2

There are 2 best solutions below

8
On BEST ANSWER

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

1
On

Try this.

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

The result you expect is list of list's. So if the code steps into second predicate it should form right type - in your code it was simple argument transaction. The right thing is to wrap it into another list to fill later with items from first 'argument'.