如何在Prolog中将if转换为完全声明?

时间:2016-12-31 09:51:20

标签: prolog declarative logical-purity

这是我的课堂问题之一。

Question

我能够用if-else创建我自己的Prolog程序但我被告知我的程序并不是完全声明的,因为它是Prolog中最基本的原则之一。

这是我的代码

$('#dropdlist').on('mouseenter mouseleave', function()  {
  var $color = $('#dropdlist :selected').text();
  $('body').css('background', $color);
  // change the text of ".color" span
  $(".color").html($color);
})

任何人都知道如何制作它"完全声明"?

2 个答案:

答案 0 :(得分:5)

如果你在代码中解决冗余问题,从逻辑中分解出数据,你会得到更多的声明性代码。

因此,对数据结构进行编码,并提供一个能够提出问题并推断其后果的“解释器”。

例如

dt(food_type,
    [indian  -> dt(spicy, [ y -> curry,   n -> curma ])
    ,chinese -> dt(fry,   [ y -> stirFry, n -> chicken ])
    ,malay   -> dt(chili, [ y -> sambal,  n -> singgang ])
    ]).

interpreter(dt(About, Choices), Choice) :-
   % present a menu for choices
   % recurse on selected path

% when it reach a leaf, just unify
interpreter(Choice, Choice).

您可能希望专门针对y / n选项菜单,但这取决于您

修改

呈现菜单并接受选择需要额外的逻辑编程,例如:

solve(Choice) :-
    dt(About, Choices),
    interpreter(dt(About, Choices), Choice).

% present a menu for choices
% recurse on selected path
interpreter(dt(About, Choices), Choice) :-
  ask_user(About, Choices, ChoiceAbout),
  interpreter(ChoiceAbout, Choice).

% when it reach a leaf, just unify
interpreter(Choice, Choice).

ask_user(About, Choices, Choice) :-
  format('your choice about ~w ?~n', [About]), % show user the context of choice
  forall(member(C->_,Choices), format('   ~w~n', [C])),
  read(U),
  memberchk(U->Choice, Choices).

% note: if memberchk above fails (user doesn't input a correct choice)
% you should provide an alternate ask_user here, otherwise ...
% just see what the code does
%

示例会话:

% /home/carlo/Desktop/pl/choices compiled into choices 0.00 sec, 0 clauses

?- solve(C).

your choice about food_type ?
   indian
   chinese
   malay
|: chinese.

your choice about fry ?
   y
   n
|: n.

C = chicken .

答案 1 :(得分:3)

CapelliC给出了一个更精致的答案,我喜欢这个答案,因为我也从他的答案中学到了一些。

这是一个更简单的版本,可以帮助连接点。

诀窍是将所需的最终结果视为一组单独的规则,例如: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="about"android:id="@+id/AboutUs" /> <item android:title="Prefs" android:id="@+id/preferences" /> <item android:title="Exit" android:id="@+id/exit" /> </menu> 然后如何找到他们。一旦我将答案从是/否更改为变量的值,其余的就是下山了。显然可以使用是/否,但这只需要额外的编码。

food(indian,spicy)
相关问题