Prolog Clear List of negative elements without using cuts

后端 未结 3 1758
慢半拍i
慢半拍i 2021-01-16 16:45

How do I write a procedure in Prolog that clears a list of integers of its negative elements and returns the result in a new list? Without using cuts but can use negation.

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 17:07

    You have it almost right. Your solution was:

    filter([],[]).
    filter([H|T],S) :-
      H<0,
      filter(T,S).
    filter([H|T],S) :-
      H>=0,
      filter(T,[H|S]).
    

    The base case and the case where the item is negative are right. The problem is with the last case. Once you checked that the item is nonnegative you know that the item will be on the resulting list. Therefore you should do the recursion and return a list that contains the element you have checked (H) and the list returned by recursion. Thus, the last clause should be

    filter([H|T],[H|S]) :-
      H>=0,
      filter(T,S).
    

提交回复
热议问题