【问题标题】:prolog. recursive function returning multiple values序言。返回多个值的递归函数
【发布时间】:2010-05-31 03:28:11
【问题描述】:

我是 Prolog 的新手。我需要声明一个查看列表的函数 [[1, 0, 0], [1, 0, 0], [1, 0, 0]] 如果值为 0,则返回其地址(将其视为双精度数组)。

我写了一个函数,基本格式如下: 功能(...,X): - 函数(由其他值调用)。

我如何编写一个函数,在每次调用时(递归)返回一个值。我可以将它们(在上述问题中)作为替代 X 吗?

【问题讨论】:

    标签: prolog


    【解决方案1】:

    您需要编写一个函数来遍历列表列表并生成包含索引的单个列表作为结果。您的示例中的结果将类似于[[0, 0], [0, 1], ...]

    为此,您需要将函数拆分为两个操作 - 一个遍历单行(嵌套列表),另一个处理外部列表(包含作为行的列表)。用于处理[1, 0, 0] 的嵌套函数如下所示(注意它需要从外部函数中获取行的索引,以便生成x、y 坐标):

    % Processes single row of the data. Parameters:
    %   row (in), row index (in), current element index (in), result (out)
    processRow([], _, _, []).
    processRow([1|Xs], R, N, Rest) :- processRow(Xs, R, N+1, Rest)
    processRow([0|Xs], R, N, [[R, N]|Rest]) :- processRow(Xs, R, N+1, Rest)
    

    第二个函数大致如下:

    % Parameters:
    %   list of lists (input), current index (input), collected indices (output)
    processOuter([], _, []).
    processOuter([Row|Rows], N, [Res|Remaining]) :-
      processRow(Row, N, 0, Res),
      processOuter(Rows, N+1, Remaining).
    

    我没有尝试代码,因此您可能需要做一些小的更正,但它应该可以让您大致了解实现的外观。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2020-10-10
      • 2021-06-11
      • 2012-03-11
      • 2017-05-14
      • 2014-07-13
      相关资源
      最近更新 更多