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

Prolog如何实现可同时判断列表升序或降序有序的谓词

你可以拆分两个判断分支,分别匹配升序、降序两种有序场景,满足任意一种即判定为有序。修改后的代码如下:

% 空列表、单元素列表天然符合有序要求
is_sorted([]).
is_sorted([_]).
is_sorted(List) :-
    is_ascending(List), !. % 匹配升序场景,加cut避免元素全相等的列表重复返回true
is_sorted(List) :-
    is_descending(List). % 匹配降序场景

% 辅助谓词:判断列表是否为非递减升序
is_ascending([]).
is_ascending([_]).
is_ascending([X,Y|T]) :-
    X =< Y,
    is_ascending([Y|T]).

% 辅助谓词:判断列表是否为非递增降序
is_descending([]).
is_descending([_]).
is_descending([X,Y|T]) :-
    X >= Y,
    is_descending([Y|T]).

测试效果参考:

  • is_sorted([1,2,3,5]) 升序列表返回 true
  • is_sorted([5,3,2,1]) 降序列表返回 true
  • is_sorted([2,2,2,2]) 元素完全相等的列表同时符合升序、降序判定,返回 true
  • is_sorted([1,3,2,4]) 乱序列表返回 false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:09:03