【问题标题】:Prolog - searching in sublist from index to end for itemProlog - 在子列表中从索引到结尾搜索项目
【发布时间】:2014-07-02 20:49:03
【问题描述】:

我希望在子列表中搜索特定字符串。有一个字符串列表(可能重复);我有一些物品;我有一个指向当前所需项目的索引;我想从索引搜索到列表的末尾,并知道 Item 是否还在。

我在这里找到的最相似的东西是Prolog: Create sublist, given two indices,但我不需要 2 个索引,我觉得它不应该那么复杂;这看起来也很接近,但我并没有真正理解它Create a sublist from a list given an index and a number of elements. Prolog。我也不认为 sublist/3 会这样做(而且它看起来已经被弃用了 - http://www.swi-prolog.org/pldoc/man?predicate=sublist/3

例如,一个列表 [Blue, Orange, Red, Yellow, Orange],一个 sequenceIndex(2),一个 'Orange' 项,我想知道 Orange 在子列表 [Red, Yellow, Orange] 中。

所以,像这样,我猜这不是如何使用 nth:

sequenceIndex(0).

sequence([blue, orange, red, yellow, orange]).

stillThere(Color) :-
   sequenceIndex(Index),
   sequence(Listcolors),
   nth(Index, Listcolors, Color).
stillThere(Color) :-
   sequenceIndex(Index),
   N is Index+1,
   sequence(Listcolors),
   nth(N, Listcolors, Color).

我会用have(X), stillThere(X) 调用它,其中Xblue(等等。它会在整个程序中发生变化)。

非常感谢!

【问题讨论】:

    标签: prolog


    【解决方案1】:

    你似乎从 0 开始,所以你的定义是

    list_index_item(Xs, I, Item) :-
       nth0(J, Xs, Item),
       J >= I.
    
    ?- list_index_item([blue, orange, red, yellow, orange], 2, orange).
    true.
    
    ?- list_index_item([blue, orange, red, yellow, orange], 2,blue).
    false.
    

    这显示了 Prolog 谓词的一般性。目标nth0(J, Xs, Item) 在所有可能的位置上都成功,但我们只对以I 开头的位置感兴趣。

    【讨论】:

    • 啊,完美!!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2023-04-10
    • 2012-04-16
    • 1970-01-01
    相关资源
    最近更新 更多