Prolog在每个非整数元素后插入整数

时间:2016-05-23 10:13:18

标签: list prolog

我有列表[r,s,2,t,3,u,v],我需要制作一个类似[r,5,s,2,t,3,u,5,v,5]的列表。规则是:对于未跟随整数的每个非整数,将在该元素之后添加5

我是Prolog的新手,到目前为止这是我的代码:

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

我知道应该有一个案例,其中S不是一个整数,但我不知道如何处理它。

编辑:
                                                                                 我更新了我的代码:

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

现在它没有问题,除非我有一个非整数作为最后一个元素。

EDIT2:
现在它运作正常。

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

1 个答案:

答案 0 :(得分:3)

以下是如何在保留的同时做到这一点!

基于 if_/3 integer_t/2我们定义:

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

使用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
相关问题