How to remove even numbers in List using Prolog

前端 未结 5 1484
隐瞒了意图╮
隐瞒了意图╮ 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:19

    Let's look at one of your clauses:

    remove_even([El|T],[T]) :- El mod 2 =:= 0.
    

    First, in the notation [El|T] El is a single item, and T is a list. Then [T] will be list inside a list, which probably is not what you want. It should be just "remove_even([El|T],T)".

    Next, your variant of the rule just copies T into the answer, not removing any even numbers from the tail. Only the first number (if it's even) will be removed. remove_even should be applied to the T also.

    In the end we should have something like this:

    remove_even([El|T], NewT) :- 
        El mod 2 =:= 0,
        remove_even(T, NewT).
    

提交回复
热议问题