【问题标题】:write a notSortedDescending function in prolog在 prolog 中写一个 notSortedDescending 函数
【发布时间】:2021-10-26 01:58:27
【问题描述】:

编写定义谓词 notSortedDescending(Numberlist) 的 Prolog 代码,当且仅当数字列表 Numberlist 未按降序排序时为真?

谁能帮我解决这个问题?我只知道如何在 Prolog 中编写排序函数。非常感谢!

notSortedDescending([x , y | z ])  :-
                 ( x => y ) -> notSortedDescending([y|z])

这就是我想出的......

【问题讨论】:

  • 这在很多方面都是错误的。先完成教程。
  • 逻辑似乎是对的,但是你需要学习prolog语法。当测试失败时,->/2 失败。所以你可能需要写.. -> .. ; true

标签: list prolog


【解决方案1】:

下面是你在 Prolog 中编写它的方法:

not_sorted_descending(L) :-
    \+ sorted_descending(L).

sorted_descending([]).
sorted_descending([_]).
sorted_descending([X,Y|Xs]) :-
    X @>= Y,
    sorted_descending([Ys|Xs]).

您需要涵盖所有元素都相等的极端情况。如果是,则列表按降序排序,因此“未按降序排序”必须失败。

定义的 sorted_descending/1 将留下一个选择点。因为你否定它没关系。

您还可以采取更实用的方法,并在列表中使用左折叠,如下所示:

not_sorted_descending([H|T]) :-
    \+ foldl(descending, T, H, _).

descending(V, V0, V) :-
    V0 @>= V.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多