1
votes

So I need to write a prolog term called doubleAll7/2 that takes two lists. The program returns true if for every 7 that occurs in the first list, the second list has two sevens in a row. Example doubleAll7([1,7,1],[1,7,7,1]) is true but doubleAll7([1,2,7],[1,2,7]) is false.

double7/2 doubles all occurrences of 7 in a list and works perfectly.

For some reason this program always returns false.

    doubleAll7([H1|T1],[H2,T2]) :-
    double7([H1|T1], L),
        L == [H2|T2].

    double7([],[]).
    double7([H|T], [H,H|Z]) :-
    H is 7,
    !,
    double7(T,Z).
    double7([H|T], [H|Z]) :-
    double7(T,Z).
1

1 Answers

0
votes

There is an obvious error: the first row

doubleAll7([H1|T1],[H2,T2])

should be

doubleAll7([H1|T1],[H2|T2])

I mean: a | instead a , as separator between H2 and T2

But, sorry: I find you solution overcomplicated.

You can avoid double7/2 (your call to double7 is unusefull because, if I'm not wrong, it's equivalent to

doubleAll7(L1, L2) :-
  double7(L1, L2).

), you can avoid is/2, you can avoi the ! and you can semplify all as

doubleAll7([], []).

doubleAll7([7 | T1], [7, 7 | T2]) :-
  doubleAll7(T1, T2).

doubleAll7([H | T1], [H | T2]) :-
  H \== 7,
  doubleAll7(T1, T2).