You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prolog如何获取列表元素索引?附跳高得分查询作业问题

Prolog实现跳次序号查询功能

实现逻辑

  • 先实现通用的辅助谓词,用于从1开始计数,返回列表中第一个匹配元素的位置,匹配不到返回-1
  • 基于已有的jump事实,封装业务查询谓词,直接传入姓名、项目类别、得分即可获得对应的跳次序号

完整代码

% 已有参考事实
jump('HUGO LENIN',2,[7,8,8,5]).
class(1, 'Long Jump',4);
class(2,'High Jump',5).

% 辅助谓词:查找列表第一个匹配元素的1基索引,匹配失败返回-1
find_first_index(Element, List, Result) :-
    find_first_index(Element, List, 1, Result).

% 匹配到元素的情况,直接返回当前计数
find_first_index(E, [E|_], Count, Count) :- !.
% 未匹配到,计数+1递归下一个元素
find_first_index(E, [_|T], Count, Result) :-
    NextCount is Count + 1,
    find_first_index(E, T, NextCount, Result).
% 列表遍历完没匹配到,返回-1
find_first_index(_, [], _, -1).

% 业务查询谓词:传入姓名、项目类别、得分,返回跳次序号
get_jump_attempt(Name, Class, Score, AttemptNo) :-
    jump(Name, Class, ScoreList),
    find_first_index(Score, ScoreList, AttemptNo).

测试示例

  • 查询get_jump_attempt('HUGO LENIN', 2, 8, Res).,返回Res = 2
  • 查询get_jump_attempt('HUGO LENIN', 2, 9, Res).,返回Res = -1
  • 查询get_jump_attempt('HUGO LENIN', 2, 5, Res).,返回Res = 4

说明

  • 代码中加入了! cut操作符,保证找到第一个匹配结果后直接返回,不会回溯返回后续重复得分的位置
  • 索引默认从1开始计数,完全符合跳次序号的需求
  • 所有边界情况都做了处理,无匹配时固定返回-1

内容的提问来源于stack exchange,提问作者Lautaro Tita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:36:06