Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: How to remove every second element of a list

Tags:

list

prolog

I need to write a program in Prolog that should remove every second element of a list. Should work this: [1,2,3,4,5,6,7] -> [1,3,5,7]

so far I have this, but it just returns "false".

r([], []). 
r([H|[T1|T]], R) :- del(T1,[H[T1|T]], R), r(R).

del(X,[X|L],L).
del(X,[Y|L],[Y|L1]):- del(X,L,L1).
like image 254
baloghi Avatar asked May 09 '11 09:05

baloghi


2 Answers

This is pretty much Landei's answer in specific Prolog syntax:

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

The second predicate is not required.

like image 91
pad Avatar answered Oct 11 '22 14:10

pad


Alternative solution using foldl/4:

fold_step(Item, true:[Item|Tail], false:Tail).
fold_step(_Item, false:Tail, true:Tail).

odd(List, Odd) :-
    foldl(fold_step, List, true:Odd, _:[]).

Usage:

?- odd([1, 2, 3, 4, 5, 6, 7], Odd).
Odd = [1, 3, 5, 7]

The idea is to go through the list, while keeping "odd/even" flag and flipping its value (false -> true, true -> false) on each element. We also gradually construct the list, by appending those elements which have "odd/even" flag equal to true, and skipping others.

like image 4
code_x386 Avatar answered Oct 11 '22 15:10

code_x386