1
votes

I want to write a predicate that will insert a given element after every element in a list and will print resulting list. I want to use recurrsion for this.

For example: my list is [1,2,3,4,5] and I want to insert 0 after every element. So the resulting list should be: [1,0,2,0,3,0,4,0,5,0].

I wrote this:

add([],X).
add([H|T],[H|[X|T1]]):-
    add(T,T1).
add([H|T],[H|T1]):-
    add(T,T1).

And I run this like: add([1,2,3], 0). but Prolog says only No. What does it mean? How can I improve this? Thanks

Edit:

It works, but shows some warnings about singleton variables:

add([], X, []).  
add([H|T], X, [H|[X|T1]]):- add(T, X, T1).  
add([H|T], X, [H|T1]):- add(T, X, T1).
2

2 Answers

1
votes

Prolog definitions do not "return" values, like in other languages. Instead, you should state facts about the relationship like so:

add(List1, InsertedElement, List2) :- ...

So, the first fact would be

add([], _, []).

I'll leave the rest as a homework exercise.

0
votes

Try this:

add( []     , _ , []       ) .      
add( [X|Xs] , V , [X,V|Ys] ) :- add(Xs,V,Ys).

And if you execute

add( [1,2,3], 0, L ).

You should get

L = [1,0,2,0,3,0]
true