【问题标题】:Split a list in prolog to atoms and integers将序言中的列表拆分为原子和整数
【发布时间】:2021-12-05 17:50:07
【问题描述】:

我是 prolog 的新手,并试图创建一个谓词来将列表分隔为原子和整数,但我已经尝试了一段时间不同的方法,但没有一个例子可以说明如何做到这一点。对我来说,这似乎是在 proleg 中要知道的基本知识,但我找不到有关如何完成此操作的示例。

例如: 分开([3,t,8,l,0,a,5,g,2],原子,整数)。原子 = [a,g,l,t],整数 = [0,2,5,3,8]

【问题讨论】:

    标签: prolog predicate


    【解决方案1】:

    在 swi-prolog 中,使用 partition/4:

    separate(List, Atoms, Integers):-
      partition(integer, List, Integers, Atoms).
    

    这假定列表中的每一项都是整数或原子

    示例运行:

    ?- separate([3,t,8,l,0,a,5,g,2],Atoms,Integers).
    Atoms = [t, l, a, g],
    Integers = [3, 8, 0, 5, 2].
    

    【讨论】:

      【解决方案2】:

      特别是如果您正在学习,请自己动手。这也允许您处理边缘情况。例如,这只是简单地丢弃了原子和整数以外的东西:

      atoms_and_ints( []     , []        , []       ) .   % The empty list doesn't have any atoms or ints.
      atoms_and_ints( [X|Xs] , [X|Atoms] , Ints     ) :-  % For a non-empty list,
        atom(X),                                          % - is the head an atom?
        !,                                                % - eliminate the choice point
        atoms_and_ints(Xs,Atoms,Ints).                    % - add it to the atoms and recurse down.
      atoms_and_ints( [X|Xs] ,    Atoms  , [X|Ints] ) :-  % Similarly,
        integer(X),                                       % - is the head an integer?
        !,                                                % - eliminate the choice point
        atoms_and_ints(Xs,Atoms,Ints).                    % - if so, add it to the Ints and recurse down.
      atoms_and_ints( [_|Xs], Atoms, Ints ) :-            % If the head of the list is something else...
        atoms_and_ints(Xs,Atoms,Ints).                    % - discard it and recurse down.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-07
        • 2012-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多