如何将函数的输出转换为列表? [英] How do I turn the outputs of a function into a list?

查看:187
本文介绍了如何将函数的输出转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输出符合特定约束条件的名称的函数.此功能很好.

I have a function that outputs names that fit a specific constraint. This function is fine.

但是我需要使用该函数来制作另一个函数,以将前一个函数的输出转换为一个列表.作为Prolog的完整入门者,我不知道如何执行此操作.

But I need to use that function to make another function that turns the outputs of the former function into a list. Being a complete beginner with Prolog, I have no clue how to do this.

我的问题是我不知道如何遍历输出以将其附加到累加器.输出名称的功能会执行此操作,然后按;"或SPACE,它将输出下一个答案,直到没有答案为止.我认为这意味着我必须多次调用该函数,然后追加它.但是我不知道需要调用多少次,因为我无法像使用[Head | Tail]的列表那样对其进行迭代.

My problem is that I don't know how to iterate over the outputs to append it to an accumulator. The function which outputs names does so, then I press ";" or SPACE and it outputs the next answer until it's out of answers. I figure this means I have to make multiple calls to the function then append it. But I don't know how many times I need to call it, since I can't iterate over it like a list with [Head|Tail].

这是我到目前为止所拥有的(虽然可能是错误的):

Here's what I have so far(although it's probably wrong):

%p1(L,X) determines if chemicals in List X are in any of the products and stores those        products in L
p1(L,X) :- p1_helper(L,X,[]).
p1_helper(L,X,Acc) :- has_chemicals(A,X),append(Acc,[A],K),L=K, p1_helper(L,X,K).

函数,输出带有查询has_chemicals(X,[化学品列表])的名称.:

function that outputs names with query has_chemicals(X,[List of Chemicals]).:

%has_chemicals(X,Is) determines if the chemicals in List Is are in the chemical list of X.
has_chemicals(X,Is) :- chemicals(X,Y), hc(Y,Is).
%hc(X,Y) determines if elements of Y are in elements of X.
hc(Y,[]).
hc(Y,[C|D]) :- isin(C,Y), hc(Y,D).

感谢您的帮助.

推荐答案

但是我需要使用该函数来制作另一个函数,以将前一个函数的输出转换为一个列表.作为Prolog的完整入门者,我不知道如何执行此操作.

But I need to use that function to make another function that turns the outputs of the former function into a list. Being a complete beginner with Prolog, I have no clue how to do this.

findall(+Template, :Goal, -Bag) : 创建实例化列表Template依次在Goal上回溯,并将结果与​​Bag统一.

findall(+Template, :Goal, -Bag): Creates a list of the instantiations Template gets successively on backtracking over Goal and unifies the result with Bag.

例如,如何收集从1到15的所有奇数:

For example, how to collect all odd numbers from 1 to 15:

odd( X ) :-
    X rem 2 =:= 1.

我们可以一一获得所有赔率.

We can get all that odds one-by-one.

?- between( 1, 15, X ), odd( X ).
X = 1 ;
X = 3 ;
X = 5 ;
X = 7 ;
X = 9 ;
X = 11 ;
X = 13 ;
X = 15.

我们可以将它们收集到一个列表中:

And we can collect them into a list:

?- findall(X, (between( 1, 15, X ), odd( X )), List).
List = [1, 3, 5, 7, 9, 11, 13, 15].

这篇关于如何将函数的输出转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆