【问题标题】:Prolog insert integer after every non integer elementProlog 在每个非整数元素后插入整数
【发布时间】:2016-05-25 19:26:00
【问题描述】:

我有列表[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).

现在它很好,除非我有一个非整数作为最后一个元素。

编辑2:
现在它可以正常工作了。

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

【问题讨论】:

  • 如果您解决了您的问题,您可以将其发布为答案而不是编辑您的问题吗?

标签: list prolog


【解决方案1】:

在保留 的同时,您可以这样做!

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

list_fived([], [])。 list_fived([X|Xs], [X|Ys]) :- if_(integer_t(X), list_fived(Xs, Ys), 过去_nonint(Xs,Ys))。 过去_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] ? ; OP 给出的预期结果百分比 不

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多