0

I am trying to learn Prolog.I am suppose to write a predicate which will place 'bubbles' before each atom in a list.The empty list is unchanged.

?-addbubbles([a,b,8,c],X).

X=[bubbles,a,bubbles,b,8,bubbles,c]

I wrote the foll Code:

Addbubbles([],[]).

addbubbles([H|T],[A|B]) :-append([bubbles],[H],A),addbubbles(T,B).

But the output is not as expected :

?- addbubbles([a,v,2,4,f],M).

M = [[bubbles,a], [bubbles,v], [bubbles,2], [bubbles,4], [bubbles,f]] ;

How can i remove the extra brackets so that i get the output as:

M = [bubbles,a, bubbles,v,bubbles,2,bubbles,4,bubbles,f];
Kijewski
  • 25,517
  • 12
  • 101
  • 143
abc
  • 153
  • 2
  • 12

1 Answers1

1

You don't need to use append/3 here. Just write down the specification verbatim:

% The empty list is left alone:
addbubbles([], []).

% Add 'bubbles' before each element in the list (recursively):
addbubbles([Element|OldTail], [bubbles,Element|NewTail]) :-
    addbubbles(OldTail, NewTail).

A list has the form [Element1, Element2, Element3… | Tail]. So you can use [bubbles,Element|NewTail] to prepend two elements.

And it works:

?- addbubbles([a,b,8,c],X).
X = [bubbles, a, bubbles, b, bubbles, 8, bubbles, c].

?- addbubbles(X, [bubbles, a, bubbles, b, bubbles, 8, bubbles, c]).
X = [a, b, 8, c].

If you want to use append/3, then you need to flatten the list. C.f. "Flatten a list in Prolog".

But look out for typos in your code. In Prolog you finish clauses with a dot, and the capitalization is important.

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143