How to remove even numbers in List using Prolog

前端 未结 5 1485
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 16:52

I need to remove all even numbers in first list and save the rest to second list. My first non-working approach was:

remove_even([],[]).
remove_even([H1|T1],         


        
5条回答
  •  执念已碎
    2021-01-14 17:16

    I mean maybe I read this wrong but don't you think you all way overthought this problem? So taking out all even elements in the first list and storing them in the second list I was able to do that just by skipping over every even element, like so:

    remove_evens([], Ys).
    remove_evens([X], [X|Ys]).
    remove_evens([X,_|Xs], [X|Ys]):-
      remove_evens(Xs, Ys), !.
    

    which in turn would give this result:

    | ?- remove_evens([1,2,3,4,5,6,7], List2).
    List2 = [1,3,5,7|_]
    

提交回复
热议问题