Prolog Clear List of negative elements without using cuts

后端 未结 3 1764
慢半拍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:01

    Using recursion for the last case,

    I'd write :

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

提交回复
热议问题