2

I have a problem shown below.

Define integer list as follows:

  1. the empty list is an integer list
  2. if L is an integer list and N is an integer then [N | L] is an integer list
  3. if L1 and L2 are integer lists, so is [L1 | L2].

Write a prolog program integer_list(L) that is satisfied if only if L is an integer list.

My program cannot implement the 3rd requirement. Can someone point out to me the mistake?

int_list([]):-!.
int_list(L):-
   is_list(L),
   L=[X|Y],
   check(L).
int_list(L):-
   L=[L1|L2],
   is_list(L1),
   is_list(L2),
   check(L1),
   check(L2).


check([]):-!.
check([X|Y]):-
  integer(X),
  check(Y).
4

2 回答 2

3

我认为你可以做的更简单,扩展检查以接受整数列表:

int_list([]).
int_list([X|Xs]) :- check(X), int_list(Xs).

check([X|Xs]) :- check(X), int_list(Xs).
check(X) :- integer(X).

注意:尽量避免不必要的削减(即做出特定的选择)。如果让 Prolog 模式匹配区分分支,代码将更容易理解,并且同样有效。

于 2013-07-29T17:08:48.377 回答
3

尝试类似:

integer_list( X      ) :-   % an unbound variable is NOT an integer list.
  var(X) ,                  %
  ! ,                       %
  fail.                     %
integer_list( []     ) .    % The empty list is an integer list.
integer_list( [X|Xs] ) :-   % A non-empty list is an integer list if:
  integer(X) ,              % - its head is an integer, and
  integer_list(Xs) .        % - its tail is an integer list.
integer_list( [X|Xs] ) :-   % A non-empty list is an integer list if:
  integer_list(X) ,         % - its head is an integer list, and
  integer_list(Xs)          % - its tail is an integer list.
  .                         % Easy!
于 2013-07-29T16:42:55.537 回答