首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你真的需要在Prolog中将Truth转换为values吗?

你真的需要在Prolog中将Truth转换为values吗?
EN

Stack Overflow用户
提问于 2011-11-08 16:53:46
回答 1查看 155关注 0票数 1

我用Prolog写了一个冒泡排序(代码如下)。它很管用,但很难闻。我对prolog还很陌生。这里是有问题的部分:

代码语言:javascript
复制
% Problem: convert the true value to something
% I can actually use.
sorted_value(X,X) :- sorted(X).
sorted_value(X,[]) :- not(sorted(X)).

奇怪的是,我需要使用此函数将True值转换为某个值(在本例中为[]),并将False值转换为另一个值才能使用它们。有没有更干净的方法?

代码语言:javascript
复制
% Bubble Sort a list.

% is the list sorted?
sorted([]).
sorted([Head|[]]).
sorted([First|[Second|Rest]]) :-
  min(First,Second,First),
  sorted([Second|Rest]).

% swap all pairs in the list that
% needs to be swapped
bubble_sort_list([], []).
bubble_sort_list([Head|[]],[Head]).
bubble_sort_list([First|[Second|Rest]], [One|Solution]) :-
  min(First,Second, One),
  max(First,Second,Two),
  bubble_sort_list([Two|Rest],Solution).

% Problem: convert the true value to something
% I can actually use.
sorted_value(X,X) :- sorted(X).
sorted_value(X,[]) :- not(sorted(X)).

% Repeatedly call bubble_sort until
% the list is sorted
bubble_sort_helper([],List, Solution) :-
  bubble_sort_list(List, SortedList),
  sorted_value(SortedList, Value),
  bubble_sort_helper(Value,SortedList, Solution).
bubble_sort_helper(A,List,List).

% this is what you call.
buuble_sort(List,Solution) :-
  bubble_sort_helper([],List,Solution).
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-08 17:45:55

每个谓词调用要么成功(可能多次),要么失败。如果您以声明的方式思考并真正描述排序列表是什么,那么似乎很少需要在程序中显式地表示真值本身。相反,在Prolog程序中放置一个像“递增(列表)”这样的谓词调用来描述排序列表的情况通常就足够了。取而代之的是调用像“递增(List,T)”这样的谓词,然后用T来区分大小写,似乎没有什么好处。为什么不直接使用谓词本身的隐式真值呢?如果您确实需要具体化the值,例如,您可以这样做,以避免两次调用递增/1:

代码语言:javascript
复制
ascending(Ls, T) :- 
    (   ascending(Ls) -> T = true
    ;   T = false
    ).

注意升序/1的真值是如何用来区分大小写的。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8047923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档