1

I have the list [r,s,2,t,3,u,v] and I need to make a list that will look like [r,5,s,2,t,3,u,5,v,5]. The rule is: for every non integer that is not followed by an integer, a 5 will be added after that element.

I am new to Prolog and this is my code so far:

insertInL([],[]).
insertInL([F,S|Tail], [F,X|Rest]) :- 
     integer(S), X = S, insertInL(Tail, Rest).

I know there should be one case where S is not an integer but I don't know hot to treat it.

Edit:
I renewed my code:

insertInL([],[]).
insertInL([F,S|T1], [F,S|T2]) :- 
    integer(S), insertInL(T1, T2).
insertInL([F,S|T1], [F,1|T2]) :- 
    \+ integer(S), insertInL([S|T1], T2).

Now it does fine unless I have a non integer as last element.

Edit2:
Now it works properly.

insertInL([],[]).
insertInL([F],[F,1]) :-
    \+ integer(F).
insertInL([F,S|T1], [F,S|T2]) :- 
    integer(S), insertInL(T1, T2),!.
insertInL([F,S|T1], [F,1|T2]) :- 
    \+ integer(S), insertInL([S|T1], T2).
repeat
  • 18,496
  • 4
  • 54
  • 166
G.G
  • 27
  • 4

1 Answers1

3

Here's how you could do it while preserving !

Based on if_/3 and integer_t/2 we define:

list_fived([], []).
list_fived([X|Xs], [X|Ys]) :-
   if_(integer_t(X),
       list_fived(Xs, Ys), 
       past_nonint(Xs, Ys)).

past_nonint([], [5]).
past_nonint([X|Xs], Ys0) :-
   if_(integer_t(X), 
       (Ys0 = [X|Ys], list_fived(Xs, Ys)),
       (Ys0 = [5|Ys], list_fived([X|Xs], Ys))).

Sample query using SICStus Prolog 4.3.2:

| ?- list_fived([r,s,2,t,3,u,v], Xs).
Xs = [r,5,s,2,t,3,u,5,v,5] ? ;      % expected result as given by the OP
no
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166