我该如何解决这个挑战?我不知道该怎么做

时间:2019-12-03 17:05:45

标签: prolog

  

给出此处提供的事实数据库:

element(air).
element(earth).
element(fire).
element(water).

compound(animal, [life,forest]).
compound(bird,  [animal,air]).
compound(cloud, [water,air]).
compound(fish,  [life,ocean]).
compound(forest, [plant,plant]).
compound(life,  [lightning,ocean,volcano]).
compound(lightning, [storm,cloud,earth]).
compound(ocean,   [water,water,water]).
compound(plant,  [earth,life]).
compound(rain,  [cloud,water]).
compound(storm,  [cloud,wind]).
compound(volcano, [fire,earth]).
compound(wind,  [air,air]).
     

写一个名为simplify(Thing,Elements)的谓词,如果   Elements是原始元素的列表(仅火,水,地球,空气)   组成原子Thing的原子。例如,

?- simplify(wind, [air,air]).
  True.   
?- simplify(volcano, X).
  X = [fire, earth]
?- simplify(lightning,X).
  X = [water, air, air, air, water, air, earth] 
?- simplify(water,X)
  X = [water].
     

注意:对于特别长的列表,SWI-Prolog控制台将   缩写输出。例如。 [value value value |...]命中'w'(对于    write ),以查看完整列表。注意:您的解决方案应适用于任何   具有这种结构的事实数据库。 (即,简单地   每个可能扩展的硬编码答案都不会通过   测试)。

1 个答案:

答案 0 :(得分:0)

我在下面附上我的方法。

element(air).
element(earth).
element(fire).
element(water).

compound(animal, [life,forest]).
compound(bird,  [animal,air]).
compound(cloud, [water,air]).
compound(fish,  [life,ocean]).
compound(forest, [plant,plant]).
compound(life,  [lightning,ocean,volcano]).
compound(lightning, [storm,cloud,earth]).
compound(ocean,   [water,water,water]).
compound(plant,  [earth,life]).
compound(rain,  [cloud,water]).
compound(storm,  [cloud,wind]).
compound(volcano, [fire,earth]).
compound(wind,  [air,air]).


checkElement([]).
checkElement([H|T]):- element(H) , checkElement(T).

com([],[]).
com([H|T],[H|Q]):- element(H) , com(T,Q).
com([H|T],[Z|Q]):- compound(H,_) , simplify(H,Z) , com(T,Q).

simplify(X,X):- element(X).
simplify(X,Y):- compound(X,Y) , checkElement(Y) .
simplify(X,Z):- compound(X,Y) , \+checkElement(Y) , com(Y,Z).

checkElement/1检查列表是否仅包含元素。

com/2用于将compound简化为元素。

输出

?-simplify(lightning,X).
  X = [[[water, air], [air, air]], [water, air], earth]

?-simplify(volcano, X).
  X = [fire, earth]
?-simplify(rain, X).
  X = [[water, air], water]
?-simplify(life, X).
  X = [[[[water, air], [air, air]], [water, air], earth], [water, water, water], [fire, earth]]

希望这就是您想要的。