gpt4 book ai didi

Prolog:如何根据类别将列表分成两个列表?

转载 作者:行者123 更新时间:2023-12-03 23:33:41 25 4
gpt4 key购买 nike

我的查询如下:

separate([eat(chips),drink(water),eat(burger),eat(banana),drink(coke)],food,drink).
food = [eat(chips),eat(burger),eat(banana)]
drink = [drink(water),drink(coke)]

我想分开列表,但我不知道怎么做。

separate(X,Cat1,Cat2):-
[Cat1|Cat2] = X,
Cat2 = X,
separate(X,Cat1,Cat2).

目前我只能使用递归来遍历列表的每个元素,但我真的不知道如何开始将它们分成单独的列表。

最佳答案

您可以使用高阶 filter 操作来获取目标进行过滤:

例如(注意Prolog中的变量必须以大写字母开头):

separate(TaggedList,Food,Drink) :-
include(isFood,TaggedList,Food), % isFood/1 will be called for each element
include(isDrink,TaggedList,Drink). % same as above

isFood(eat(_)). % no need to be complex; just succeed if argument matches
isDrink(drink(_)). % same as above

所以:

?- separate(
[eat(chips),drink(water),eat(burger),eat(banana),drink(coke)],
Food,Drink).
Food = [eat(chips), eat(burger), eat(banana)],
Drink = [drink(water), drink(coke)].

关于Prolog:如何根据类别将列表分成两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64585487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com